C Programming By OpenGurukul Team www.opengurukul.com
C Programming Introduction www.opengurukul.com 2
Introduction : History 1960 ALGOL In te rn a tion a l G rou p 1967 BCPL Ma rtin R ic h a rd s 1970 B Ke n T h om p s on 1972 Traditional C D e n n is R itc h e www.opengurukul.com 3
Introduction : Features Extensive use of function calls Structured language Pointer implementation - extensive use of pointers for memory, array, structures and functions. C has now become a widely used professional language for various reasons. General purpose programming language. Helps in development of both system as well as application software. C is a highly portable language. This means it can be run on different machines . www.opengurukul.com 4
Introduction : Program Structure Documentation Preprocessor directives / header files Type definitions Function prototypes -- declare function types and variables passed to function. The main() function Other Functions www.opengurukul.com 5
Introduction : C program : Example Program : 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"); $ } www.opengurukul.com 6
Introduction : Input and output The 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. www.opengurukul.com 7 For floating point, to point 2 characters after decimal point, use %.2f
Introduction : I/O : Example Program : #include <stdio.h> OUTPUT : Enter a number : 10 main() number = 10 { int x; printf("Enter a number : "); scanf("%d", &x); printf("number = %dn", x); return 0; } www.opengurukul.com 8
Comments Single line comment can be specified using // // single line comment Multi line comment can be specified using /* */ /* * Multi line comment 1 * Multi line comment 2 */ www.opengurukul.com 9
C programming Data Types & Variables www.opengurukul.com 10
Identifiers Identifiers are names given to the elements such as variables, arrays and functions that are used in a program Basically, these identifiers are sequence of alphabets and digits There are certain rules that govern the formation of identifiers, based on those rules the following are the VALID and INVALID identifiers : Valid identifiers: Marks, TOTAL_MARKS , gross_salary_1998, Area_of_circle(), Num[20] Invalid identifiers: 8ab, TOTAL MARK, Gross-salary-1997, Area_ _ of _ _ circle www.opengurukul.com 11
Data Types & Sizes Data types Qualifiers - unsigned & signed char - single byte - can store one applies to char and integer character default may be signed or unsigned (it int - integer - generally natural size depends on the platform). float - for single precision floating point Range double - 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 bytes long int - 4 bytes (32-bit systems), 8 bytes(64-bit systems) www.opengurukul.com 12
Data Types & Sizes Ty p e S iz e Rang e fo rm char 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 255 char in t 2 b y te -3 2 7 6 8 to % d -2 5 5 0 -5 32767 u n s ig n e d in t 2 b y te 0 to 6 5 5 3 5 % u 25u 32768u lon 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 + 2147483647 u n s ig n e d 4 b y te 0 to % lu 1 0 0 lu 5 1 lu lon g 4294967295 floa t 4 b y te ± 3 .4 * 1 0 ^ ± 3 8 %f -3 .5 f 7 .5 f d ou b le 8 b y te ± 1 .7 * 1 0 ^ ± 3 0 8 % lf -3 .5 7 .5 lon g d ou b le 1 0 b y te ± 3 .4 * % L f -3 .5 L 7 .5 L 10^ ± 4932 www.opengurukul.com 13
Data types: Example #include <stdio.h> Output: int main(void) { sizeof char = 1 printf("sizeof char = %dn", sizeof(char)); sizeof short = 2 printf("sizeof short = %dn", sizeof(short)); sizeof int = 4 printf("sizeof int = %dn", sizeof(int)); sizeof long = 4 printf("sizeof long = %dn", sizeof(long)); sizeof float = 4 printf("sizeof float = %dn", sizeof(float)); sizeof double = 8 printf("sizeof double = %dn", sizeof(double)); return 0; } www.opengurukul.com 14
Variables It is a data name that is used to store a data value. Variables can take different values at different times during execution. All the variables must be declared before they are used. Example: Declaration: int x; float y; Initialization: x=10; y=10.5; www.opengurukul.com 15
Variable Names There are certain conditions to be followed before the declaration of a variable : . They must begin with a letter . Uppercase and lowercase are significant . It should not be a keyword . White space is not allowed Examples of valid variable names: John value x1 T_cut Examples of Invalid variable names: 123 % 21th (area) The underscore "_" counts as a letter. It is very useful for readability of long variable names. Don't begin your variable name with "_" as system library routines uses16 www.opengurukul.com such names.
Variable Names Names 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. Don't 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. www.opengurukul.com 17
Variable Declarations All 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 in int 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 in int i = 0; www.opengurukul.com 18
Constants The term constant means that it does not change during the execution of program There are four basic types of constants in C 1.Integer constants 2.Floating-point constants 3.Character constants 4.String constants Comma 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. www.opengurukul.com 19
Constants : Integer : Example #include <stdio.h> Output : #include <stdlib.h> x = 10 int main() y = 255 { int x = 012; int y = 0xFF; printf("x = %dn", x); printf("y = %dn", y); return 0; } www.opengurukul.com 20
Constant : Character : Example #include<stdio.h> Output int main() c=x { const char c = 'x'; printf(“c = %cn”, c); return 0; } www.opengurukul.com 21
Constant : String : Example #include<stdio.h> Output Int main() s = Open Gurukul { const char *s = ”Open Gurukul”; printf(“s = %sn”, s); return 0; } www.opengurukul.com 22
C Programming Operators www.opengurukul.com 23
Operators An operator is a symbol that tells the compiler to perform specific operation. Operator are classified into 3 types based upon no. of operands. Unary operator: Required only one operand Binary operator: Required only two operand Ternary: Required only three operand www.opengurukul.com 24
OPERATORS Unary 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 www.opengurukul.com 25
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 www.opengurukul.com 26 in c re m e n t/d e c + + , -- re m e n t
Operators : Arithmetic : Example PROGRAM: #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 www.opengurukul.com 27
BITWISE OPERATOR The operator which act on the internal bits of respective bytes, are known as bitwise operator. C provides 6 bit wise operators for bit manipulation. & Bitwise and | Bitwise or ^ Bitwise exclusive or << Left shift >> Right shift ~ one’s complement www.opengurukul.com 28
& Bitwise-AND operator The & operator performs a bitwise AND on two integers. a b a&b 0 0 0 0 1 0 1 0 0 1 1 1 Example: 2&3 2 0000000000000010 3 0000000000000011 2&3 0000000000000010 2 www.opengurukul.com 29
| 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 1 Example: 2|3 2 0000000000000010 3 0000000000000011 2|3 0000000000000011 www.opengurukul.com 3 30
^ 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 0 Example: 2^3 2 0000000000000010 3 0000000000000011 2^3 0000000000000001 1 www.opengurukul.com 31
Operators : Bit-wise : Example PROGRAM : OUTPUT : 231 #include<stdio.h> #include<stdlib.h> int main() { printf(“%d %d %d”, 2&3, 2|3, 2^3); return 0; } www.opengurukul.com 32
Left Shift The 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=104 13 (00001101) 104 (01101000) www.opengurukul.com 33
Right Shift The 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=3 52 (00110100) 3 (00000011) www.opengurukul.com 34
INCREMENT and DECREMENT OPERATOR increment 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 www.opengurukul.com 35
Operators : Pre/Post Inc/Dec : Example PROGRAM: #include <stdio.h> Output: #include <stdlib.h> x = 11, y = 10 x = 10, y = 10 int 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); } www.opengurukul.com 36
Operators : Assignment It 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; www.opengurukul.com 37
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 www.opengurukul.com 38
Operators : Relational These 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 www.opengurukul.com 39
Operators : Logical The 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 www.opengurukul.com 40
&& Logical-AND operator It perform conditional-AND on two boolean expression. a b a&&b falsefalse false falsetrue false true false false true true true Example: 2&&3 2 true 3 true 2&&3 true 1 www.opengurukul.com 41
|| Logical-OR operator It perform conditional-OR on two boolean expression. a b a||b false false false false true true true false true true true true Example: 2&&0 2 true 0 false 2||0 true 1 www.opengurukul.com 42
! Logical-NOT operator It performs logical not operation. a !a false true true false Example: 2(true) !2->false->0 www.opengurukul.com 43
Operators : Logical : Example PROGRAM: OUTPUT : #include<stdio.h> ONE #include<stdlib.h> main() { if (!1) printf("NOT ONEn"); else printf("ONEn"); } www.opengurukul.com 44
Operators : Comma The comma operator is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type). int a=1, b=2, c=3, i; // not an operator here i = (a, b); // stores b into i i = a, b; // stores a into i i = (a += 2, a + b); // increases a by 2, then stores a+b = 3+2 into i i = a += 2, a + b; // increases a by 2, then stores a = 3 into i www.opengurukul.com 45
Operators : Comma : Example PROGRAM: 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; } www.opengurukul.com 46
TERNARY OPERATOR Defines 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. www.opengurukul.com 47
Operators : Ternary : Example PROGRAM: OUTPUT : #include <stdio.h> Enter first value : 3 #include <stdlib.h> Enter second value : 4 main() { 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); } www.opengurukul.com 48
Operators : sizeof() The sizeof() operator can be used PROGRAM : to figure out size of data type. #include <stdio.h> The sizeof() is not a function whose 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 www.opengurukul.com 49
C Programming Control Flow www.opengurukul.com 50
Control structure : Decisions If-statement If-else-statement switch-statement www.opengurukul.com 51
Control Flow : If Statement The if statement used to control the flow of execution of statement. The general from of a simple if statement is if ( test expression ) { statement-block; } www.opengurukul.com 52
Control Flow: if Statement : Example PROGRAM: OUTPUT : main() { Congratulations! int grade = 68; You passed! if (grade > 60) { printf(“congratulations!”); printf(“You passed!”); } } www.opengurukul.com 53
Control flow : if else Statements The 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) } www.opengurukul.com 54
Control flow: if else : Example PROGRAM : OUTPUT : main() Sorry you failed { int grade = 58; if (grade > 60) { printf(“congratulations!”); printf(“You passed!”); } else { printf(“Sorry you failed”); } } www.opengurukul.com 55
Control flow : Switch Statement Switch 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 www.opengurukul.com 56 break;
Control flow : Switch : Example PROGRAM: main() { OUTPUT: int option = 2; B switch(option) { case 1: printf(“A”); break; case 2: printf(“B”); break; default : printf(“def”); break; } www.opengurukul.com 57 }
Looping control structure while loop do-while loop for loop www.opengurukul.com 58
Control flow : while Statement The basic format of the while statement is while (test condition) { body of the loop } www.opengurukul.com 59
Control flow : while : Example PROGRAM: OUTPUT : main() { 01234 int X = 0; while ( X < 5 ) { printf(“ %d ”, X); X++; } } www.opengurukul.com 60
Control flow : do while Statement The do while loop takes the following form : do { body of the loop } while ( test-condition) ; www.opengurukul.com 61
Control flow : do while : Example PROGRAM: OUTPUT : main() 01234 { int X = 0; do { printf(“ %d ”, X); X++; } while ( X < 5 ); } www.opengurukul.com 62
Control Flow : For Statement The general form of the for loop is for (initialization; test condition; increment / decrement) { body of the loop } www.opengurukul.com 63
Control flow : For Loop : Example PROGRAM: OUTPUT: main() 01234 { int i ; for (i = 0; i < 5; i++) { printf(“ %d “,i); } } www.opengurukul.com 64
C Programming Functions www.opengurukul.com 65
Functions : Introduction A 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>; } www.opengurukul.com 66 If the return type is "void", the function doesn't return any value.
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; www.opengurukul.com 67
Recursion Recursion is a programming technique in which function calls itself. It repeats the same code, and in some ways it is similar to looping. www.opengurukul.com 68
Recursion Example PROGRAM: 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; www.opengurukul.com 69 }
Function : Calling a function While calling a parametrized function, we have to pass some values. There are two ways to call a function, 1. Call by Value 2. 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. www.opengurukul.com 70
Functions : Call by Value : Example Program: Output: void modify(int,int); modify: x=100, y=200 void main() { main: x=10, y=20 int 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); } www.opengurukul.com 71
Functions : Call by Reference : Example Program: Output: void modify(int *,int *); modify: x=100, y=200 void main() { main: x=100, y=200 int 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); www.opengurukul.com 72 }
C Programming Arrays www.opengurukul.com 73
Arrays : introduction 1. 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 etc 4. An array elements index or subscript begins with number zero. www.opengurukul.com 74
Arrays : Example Program: 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 } www.opengurukul.com 75
Arrays : Array Elements The 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: www.opengurukul.com 76
Arrays : Initialization The 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 www.opengurukul.com 77
Arrays : Initialization without Size Example : 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. www.opengurukul.com 78
Arrays : Example Program: #include<stdio.h> Output: #define MAX_CLASS 5 students in class 1 : 30 Int 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]); www.opengurukul.com 79 }
Arrays : Multidimensional Array Often 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]; www.opengurukul.com 80
Arrays : Multidimensional Array : Example Program: 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; } www.opengurukul.com // for printing all the values of the array 81
Arrays : Array as Parameters 1.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. www.opengurukul.com 82
Arrays : Array as Parameter : Example PROGRAM: 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 4 int main() { int toppers_roll_no[NUM_TOPPERS] = {10, 20, 30,432}; print_students(toppers_roll_no, NUM_TOPPERS); return 0; } www.opengurukul.com 83
C Programming Module : Structure www.opengurukul.com 84
Basics of Structures A 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 ; www.opengurukul.com 85 The keyword "struct" is followed by a structure name.
Structures : Access Members/Fields emp_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.member Example e.id e.emp_name www.opengurukul.com 86
Structures : Example /* Example : struct.c */ Output : #include <stdio.h> #include <string.h> $ gcc -o struct struct.c typedef 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); www.opengurukul.com 87 }
Pointers to Structure The 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_name Example: emp_t *e_p; /* pointer to struct */ e_p->emp_id e_p->emp_name www.opengurukul.com 88
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); } www.opengurukul.com 89
Self-referential Structure A 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 structures struct node { int value; struct node *next; }; www.opengurukul.com 90
C Programming Pointers www.opengurukul.com 91
Pointers : Introduction Definition-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 www.opengurukul.com 92
Pointers : Need of Pointers These 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. www.opengurukul.com 93
Pointers : Declaration & Initialization : Example Program: #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 x printf(“ p = %un”,p); // the address of x printf(“&p = %un”, &p); // the address of the pointer } www.opengurukul.com 94
Pointers : Arithmetic Operation Pointer 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. www.opengurukul.com 95
Address Arithmetic Example Program: #include <stdio.h> Output: void main() a = 30, b = 6 { x = 30 int 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); www.opengurukul.com 96 }
Pointers : Character pointers in C In 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 0 cp = “matsya”; cp www.opengurukul.com 97
Pointers : Char pointer : Example Program: Output: #include<stdio.h> Mataya void main() { char *cptr; cptr=“Matsya”; printf(“%s”,cptr); while(*cptr!=‘0’) { if(*cptr==‘s’) *cptr=‘a’; printf(“%c”,*cptr); cptr++; } } www.opengurukul.com 98
Pointers : Pointers to Arrays Pointer 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 www.opengurukul.com 99
Pointers : Pointers to Array : Example Program : Output: # include<stdio.h> a[0] = 1 void main() p+0 = 1 { a[1] = 23 int a[]={1,23,45}; p+1 = 23 int *p, i; p=&a[0]; a[2] = 45 for(i=0;i<3;i++) p+2 = 45 { printf("a[%d] = %dn",i,a[i]); printf("p+%d=%dn",i,*(p+i)); } } www.opengurukul.com 100
Pointers : Command line arguments main() function has two arguments. The first is number of command line arguments i.e., int argc The second is a pointer to an array of character strings that contain the arguments one per string i.e., char *argv[] www.opengurukul.com 101
Command line Argument : Example Program: cmd.c bin>tcc cmd.c #include<stdio.h> bin>cmd.exe this is a program main(int argc, char *argv[]) Output: { this is a program int i; for(i=1;i<argc;i++) { printf(“%8s”,argv[i]); } } www.opengurukul.com 102
C Programming Input & Output www.opengurukul.com 103
IO : File input & output The 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.h The standard library functions for file input and output are included in the c standard library header <stdio.h> Type We 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. Functions Reading from or writing to a file in C requires 3 basic steps: Open the file. Do reading/writing. www.opengurukul.com 104 Close the file.
Opening a file using fopen A filepointer is used to open a file present using the format, FILE* fp; FILE* fopen(char *name, char *mode); For opening a file fp = fopen(name of file, mode); Mode Normal Access r Open existing file for "r"eading w Open file for "w"riting, destroying the contents; create if necessary a "A"ppend at end of file; create if necessary Update Access (for fixed-length records) r+ Open existing file for "r"eading & writing w+ Open file for reading & "w"riting, destroying the contents; create if necessary a+ Open file for reading & writing -- all writing is "a"ppended to the end of the file; create if necessary www.opengurukul.com 105
Opening a file using fopen For checking whether a file exists give fopen(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 file int 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. www.opengurukul.com 106
Opening a file using fopen getchar 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 used. int 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. www.opengurukul.com 107
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"); www.opengurukul.com 108
Line I/O fgets char *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. fputs int 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. www.opengurukul.com 109
Formatted Output using printf The output function printf translates internal values to characters. For example int 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. www.opengurukul.com 110
Formatted Output using printf u 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 d's is given by the recision e,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 www.opengurukul.com % no argument is converted; print a % 111
Formatted Output using printf A 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 effects The 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: www.opengurukul.com 112 :%-15.10s: :hello,wor :
Formatted Input using scanf scanf 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 Conversions Character | Input Data | Argument Type d | decimal integer | int * u | unsigned decimal integer | unsigned int * www.opengurukul.com 113 c | character | char *
Formatted Input using scanf s | 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 www.opengurukul.com 114
Error Handling stderr The 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. exit The 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 www.opengurukul.com uses this one as a sub process. 115
Char I/O fgetc() int fgetc(FILE *fp); The fgetc function is used to read a character from a stream If successful, fgetc returns the next byte or character from the stream If unsuccessful, fgetc returns EOF. getc() macro behaves similar to fgetc() it may evaluate its arguments more than once. getchar() int getchar(void); function takes no argument. www.opengurukul.com 116 equivalent to getc(stdin).
Char I/O fputc() int fputc(int c, FILE *stream); The fputc function is used to write a character from a stream to the file If successful, fputc writes the next byte or character from the stream If unsuccessful, fgetc returns EOF. www.opengurukul.com 117
C Programming Module : Strings www.opengurukul.com 118
Strings Strings are defined as an array of characters. We can used following statement to define a string of 5 characters char 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] */ www.opengurukul.com 119
String Literals A 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 www.opengurukul.com 120
String Terminator A 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 www.opengurukul.com 121
String format specifier We 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); www.opengurukul.com 122 }
string length : strlen function The function strlen() can be used to Example: Calculate lengh of string calculate the length of the string. literals "Hello World" It doesn't 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 www.opengurukul.com of Hello World = 11 123
string copy : strcpy function We 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 www.opengurukul.com 124
string concatenation : strcat function We 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 www.opengurukul.com 125
string compare : strcmp function We 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); www.opengurukul.com 126
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 www.opengurukul.com 127
search for string in string : strstr The 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); www.opengurukul.com 128
C Programming Storage Classes www.opengurukul.com 129
Scope of Variables A 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 shouldwww.opengurukul.com be defined in any one source file 130
External Variables The 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. www.opengurukul.com 131
External Variables:Example Header File : common.h Second Source File : second.c extern 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, www.opengurukul.com ev = 5 132
Static Variables Static 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. www.opengurukul.com 133
Static Variables : Example PROGRAM: OUTPUT : #include <stdio.h> 2 #include <stdlib.h> 3 void add() { 4 static int x = 1; x++; printf("%dn", x); } main() { add(); // return 2 add(); // return 3 add(); // return 4 } www.opengurukul.com 134
Storage Classes : Register Variables The 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; www.opengurukul.com 135
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 0 re g is te r b od y b od y G a rb a g e v a lu e www.opengurukul.com 136
Storage Classes : Initialization The static and extern variables are initialized to 0 by compiler An automatic variable remains uninitialized and it will contain garbage. You can initialize a variable while defining it. www.opengurukul.com 137
Storage Classes : Initialization : Example extern 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); } www.opengurukul.com 138
C Programming Module Miscellaneous www.opengurukul.com 139
The typedef The 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 */ www.opengurukul.com 140
Union A 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; }; www.opengurukul.com 141
Union:Access union-name.member : access union fields using union variable union-pointer->member : access union fields using pointer to union variable Example: www.opengurukul.com 142
Bit-fields When 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 04 or 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. www.opengurukul.com 143
Bit-fields Certain 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).... is 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. www.opengurukul.com 144

OpenGurukul : Language : C Programming

  • 1.
    C Programming By OpenGurukul Team www.opengurukul.com
  • 2.
    C Programming Introduction www.opengurukul.com 2
  • 3.
    Introduction : History 1960 ALGOL In te rn a tion a l G rou p 1967 BCPL Ma rtin R ic h a rd s 1970 B Ke n T h om p s on 1972 Traditional C D e n n is R itc h e www.opengurukul.com 3
  • 4.
    Introduction : Features Extensiveuse of function calls Structured language Pointer implementation - extensive use of pointers for memory, array, structures and functions. C has now become a widely used professional language for various reasons. General purpose programming language. Helps in development of both system as well as application software. C is a highly portable language. This means it can be run on different machines . www.opengurukul.com 4
  • 5.
    Introduction : ProgramStructure Documentation Preprocessor directives / header files Type definitions Function prototypes -- declare function types and variables passed to function. The main() function Other Functions www.opengurukul.com 5
  • 6.
    Introduction : Cprogram : Example Program : 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"); $ } www.opengurukul.com 6
  • 7.
    Introduction : Inputand output The 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. www.opengurukul.com 7 For floating point, to point 2 characters after decimal point, use %.2f
  • 8.
    Introduction : I/O: Example Program : #include <stdio.h> OUTPUT : Enter a number : 10 main() number = 10 { int x; printf("Enter a number : "); scanf("%d", &x); printf("number = %dn", x); return 0; } www.opengurukul.com 8
  • 9.
    Comments Single line commentcan be specified using // // single line comment Multi line comment can be specified using /* */ /* * Multi line comment 1 * Multi line comment 2 */ www.opengurukul.com 9
  • 10.
    C programming DataTypes & Variables www.opengurukul.com 10
  • 11.
    Identifiers Identifiers are namesgiven to the elements such as variables, arrays and functions that are used in a program Basically, these identifiers are sequence of alphabets and digits There are certain rules that govern the formation of identifiers, based on those rules the following are the VALID and INVALID identifiers : Valid identifiers: Marks, TOTAL_MARKS , gross_salary_1998, Area_of_circle(), Num[20] Invalid identifiers: 8ab, TOTAL MARK, Gross-salary-1997, Area_ _ of _ _ circle www.opengurukul.com 11
  • 12.
    Data Types &Sizes Data types Qualifiers - unsigned & signed char - single byte - can store one applies to char and integer character default may be signed or unsigned (it int - integer - generally natural size depends on the platform). float - for single precision floating point Range double - 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 bytes long int - 4 bytes (32-bit systems), 8 bytes(64-bit systems) www.opengurukul.com 12
  • 13.
    Data Types &Sizes Ty p e S iz e Rang e fo rm char 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 255 char in t 2 b y te -3 2 7 6 8 to % d -2 5 5 0 -5 32767 u n s ig n e d in t 2 b y te 0 to 6 5 5 3 5 % u 25u 32768u lon 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 + 2147483647 u n s ig n e d 4 b y te 0 to % lu 1 0 0 lu 5 1 lu lon g 4294967295 floa t 4 b y te ± 3 .4 * 1 0 ^ ± 3 8 %f -3 .5 f 7 .5 f d ou b le 8 b y te ± 1 .7 * 1 0 ^ ± 3 0 8 % lf -3 .5 7 .5 lon g d ou b le 1 0 b y te ± 3 .4 * % L f -3 .5 L 7 .5 L 10^ ± 4932 www.opengurukul.com 13
  • 14.
    Data types: Example #include<stdio.h> Output: int main(void) { sizeof char = 1 printf("sizeof char = %dn", sizeof(char)); sizeof short = 2 printf("sizeof short = %dn", sizeof(short)); sizeof int = 4 printf("sizeof int = %dn", sizeof(int)); sizeof long = 4 printf("sizeof long = %dn", sizeof(long)); sizeof float = 4 printf("sizeof float = %dn", sizeof(float)); sizeof double = 8 printf("sizeof double = %dn", sizeof(double)); return 0; } www.opengurukul.com 14
  • 15.
    Variables It is adata name that is used to store a data value. Variables can take different values at different times during execution. All the variables must be declared before they are used. Example: Declaration: int x; float y; Initialization: x=10; y=10.5; www.opengurukul.com 15
  • 16.
    Variable Names There arecertain conditions to be followed before the declaration of a variable : . They must begin with a letter . Uppercase and lowercase are significant . It should not be a keyword . White space is not allowed Examples of valid variable names: John value x1 T_cut Examples of Invalid variable names: 123 % 21th (area) The underscore "_" counts as a letter. It is very useful for readability of long variable names. Don't begin your variable name with "_" as system library routines uses16 www.opengurukul.com such names.
  • 17.
    Variable Names Names aremade 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. Don't 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. www.opengurukul.com 17
  • 18.
    Variable Declarations All variablesmust 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 in int 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 in int i = 0; www.opengurukul.com 18
  • 19.
    Constants The term constantmeans that it does not change during the execution of program There are four basic types of constants in C 1.Integer constants 2.Floating-point constants 3.Character constants 4.String constants Comma 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. www.opengurukul.com 19
  • 20.
    Constants : Integer: Example #include <stdio.h> Output : #include <stdlib.h> x = 10 int main() y = 255 { int x = 012; int y = 0xFF; printf("x = %dn", x); printf("y = %dn", y); return 0; } www.opengurukul.com 20
  • 21.
    Constant : Character: Example #include<stdio.h> Output int main() c=x { const char c = 'x'; printf(“c = %cn”, c); return 0; } www.opengurukul.com 21
  • 22.
    Constant : String: Example #include<stdio.h> Output Int main() s = Open Gurukul { const char *s = ”Open Gurukul”; printf(“s = %sn”, s); return 0; } www.opengurukul.com 22
  • 23.
    C Programming Operators www.opengurukul.com 23
  • 24.
    Operators An operator isa symbol that tells the compiler to perform specific operation. Operator are classified into 3 types based upon no. of operands. Unary operator: Required only one operand Binary operator: Required only two operand Ternary: Required only three operand www.opengurukul.com 24
  • 25.
    OPERATORS Unary 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 www.opengurukul.com 25
  • 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 www.opengurukul.com 26 in c re m e n t/d e c + + , -- re m e n t
  • 27.
    Operators : Arithmetic: Example PROGRAM: #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 www.opengurukul.com 27
  • 28.
    BITWISE OPERATOR The operator which act on the internal bits of respective bytes, are known as bitwise operator. C provides 6 bit wise operators for bit manipulation. & Bitwise and | Bitwise or ^ Bitwise exclusive or << Left shift >> Right shift ~ one’s complement www.opengurukul.com 28
  • 29.
    & Bitwise-AND operator The& operator performs a bitwise AND on two integers. a b a&b 0 0 0 0 1 0 1 0 0 1 1 1 Example: 2&3 2 0000000000000010 3 0000000000000011 2&3 0000000000000010 2 www.opengurukul.com 29
  • 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 1 Example: 2|3 2 0000000000000010 3 0000000000000011 2|3 0000000000000011 www.opengurukul.com 3 30
  • 31.
    ^ Bitwise exclusive-ORoperator 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 0 Example: 2^3 2 0000000000000010 3 0000000000000011 2^3 0000000000000001 1 www.opengurukul.com 31
  • 32.
    Operators : Bit-wise: Example PROGRAM : OUTPUT : 231 #include<stdio.h> #include<stdlib.h> int main() { printf(“%d %d %d”, 2&3, 2|3, 2^3); return 0; } www.opengurukul.com 32
  • 33.
    Left Shift The shift-leftoperator (<<, 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=104 13 (00001101) 104 (01101000) www.opengurukul.com 33
  • 34.
    Right Shift The shift-rightoperator (>>, 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=3 52 (00110100) 3 (00000011) www.opengurukul.com 34
  • 35.
    INCREMENT and DECREMENT OPERATOR increment 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 www.opengurukul.com 35
  • 36.
    Operators : Pre/PostInc/Dec : Example PROGRAM: #include <stdio.h> Output: #include <stdlib.h> x = 11, y = 10 x = 10, y = 10 int 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); } www.opengurukul.com 36
  • 37.
    Operators : Assignment Itis 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; www.opengurukul.com 37
  • 38.
    Operators : CompoundOperators 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 www.opengurukul.com 38
  • 39.
    Operators : Relational Theseoperators 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 www.opengurukul.com 39
  • 40.
    Operators : Logical Theoperators, generally used in conditional statements. These operators are used to check between two or more conditions. Operator Meaning && Logical AND || Logical OR ! Logical NOT www.opengurukul.com 40
  • 41.
    && Logical-AND operator Itperform conditional-AND on two boolean expression. a b a&&b falsefalse false falsetrue false true false false true true true Example: 2&&3 2 true 3 true 2&&3 true 1 www.opengurukul.com 41
  • 42.
    || Logical-OR operator Itperform conditional-OR on two boolean expression. a b a||b false false false false true true true false true true true true Example: 2&&0 2 true 0 false 2||0 true 1 www.opengurukul.com 42
  • 43.
    ! Logical-NOT operator Itperforms logical not operation. a !a false true true false Example: 2(true) !2->false->0 www.opengurukul.com 43
  • 44.
    Operators : Logical: Example PROGRAM: OUTPUT : #include<stdio.h> ONE #include<stdlib.h> main() { if (!1) printf("NOT ONEn"); else printf("ONEn"); } www.opengurukul.com 44
  • 45.
    Operators : Comma Thecomma operator is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type). int a=1, b=2, c=3, i; // not an operator here i = (a, b); // stores b into i i = a, b; // stores a into i i = (a += 2, a + b); // increases a by 2, then stores a+b = 3+2 into i i = a += 2, a + b; // increases a by 2, then stores a = 3 into i www.opengurukul.com 45
  • 46.
    Operators : Comma: Example PROGRAM: 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; } www.opengurukul.com 46
  • 47.
    TERNARY OPERATOR Defines aconditional 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. www.opengurukul.com 47
  • 48.
    Operators : Ternary: Example PROGRAM: OUTPUT : #include <stdio.h> Enter first value : 3 #include <stdlib.h> Enter second value : 4 main() { 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); } www.opengurukul.com 48
  • 49.
    Operators : sizeof() Thesizeof() operator can be used PROGRAM : to figure out size of data type. #include <stdio.h> The sizeof() is not a function whose 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 www.opengurukul.com 49
  • 50.
    C Programming ControlFlow www.opengurukul.com 50
  • 51.
    Control structure :Decisions If-statement If-else-statement switch-statement www.opengurukul.com 51
  • 52.
    Control Flow :If Statement The if statement used to control the flow of execution of statement. The general from of a simple if statement is if ( test expression ) { statement-block; } www.opengurukul.com 52
  • 53.
    Control Flow: ifStatement : Example PROGRAM: OUTPUT : main() { Congratulations! int grade = 68; You passed! if (grade > 60) { printf(“congratulations!”); printf(“You passed!”); } } www.opengurukul.com 53
  • 54.
    Control flow :if else Statements The 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) } www.opengurukul.com 54
  • 55.
    Control flow: ifelse : Example PROGRAM : OUTPUT : main() Sorry you failed { int grade = 58; if (grade > 60) { printf(“congratulations!”); printf(“You passed!”); } else { printf(“Sorry you failed”); } } www.opengurukul.com 55
  • 56.
    Control flow :Switch Statement Switch 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 www.opengurukul.com 56 break;
  • 57.
    Control flow :Switch : Example PROGRAM: main() { OUTPUT: int option = 2; B switch(option) { case 1: printf(“A”); break; case 2: printf(“B”); break; default : printf(“def”); break; } www.opengurukul.com 57 }
  • 58.
    Looping control structure whileloop do-while loop for loop www.opengurukul.com 58
  • 59.
    Control flow :while Statement The basic format of the while statement is while (test condition) { body of the loop } www.opengurukul.com 59
  • 60.
    Control flow :while : Example PROGRAM: OUTPUT : main() { 01234 int X = 0; while ( X < 5 ) { printf(“ %d ”, X); X++; } } www.opengurukul.com 60
  • 61.
    Control flow :do while Statement The do while loop takes the following form : do { body of the loop } while ( test-condition) ; www.opengurukul.com 61
  • 62.
    Control flow :do while : Example PROGRAM: OUTPUT : main() 01234 { int X = 0; do { printf(“ %d ”, X); X++; } while ( X < 5 ); } www.opengurukul.com 62
  • 63.
    Control Flow :For Statement The general form of the for loop is for (initialization; test condition; increment / decrement) { body of the loop } www.opengurukul.com 63
  • 64.
    Control flow :For Loop : Example PROGRAM: OUTPUT: main() 01234 { int i ; for (i = 0; i < 5; i++) { printf(“ %d “,i); } } www.opengurukul.com 64
  • 65.
    C Programming Functions www.opengurukul.com 65
  • 66.
    Functions : Introduction Ablock 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>; } www.opengurukul.com 66 If the return type is "void", the function doesn't return any value.
  • 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; www.opengurukul.com 67
  • 68.
    Recursion Recursion is aprogramming technique in which function calls itself. It repeats the same code, and in some ways it is similar to looping. www.opengurukul.com 68
  • 69.
    Recursion Example PROGRAM: 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; www.opengurukul.com 69 }
  • 70.
    Function : Callinga function While calling a parametrized function, we have to pass some values. There are two ways to call a function, 1. Call by Value 2. 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. www.opengurukul.com 70
  • 71.
    Functions : Callby Value : Example Program: Output: void modify(int,int); modify: x=100, y=200 void main() { main: x=10, y=20 int 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); } www.opengurukul.com 71
  • 72.
    Functions : Callby Reference : Example Program: Output: void modify(int *,int *); modify: x=100, y=200 void main() { main: x=100, y=200 int 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); www.opengurukul.com 72 }
  • 73.
    C Programming Arrays www.opengurukul.com 73
  • 74.
    Arrays : introduction 1.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 etc 4. An array elements index or subscript begins with number zero. www.opengurukul.com 74
  • 75.
    Arrays : Example Program: 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 } www.opengurukul.com 75
  • 76.
    Arrays : ArrayElements The 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: www.opengurukul.com 76
  • 77.
    Arrays : Initialization Theelements 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 www.opengurukul.com 77
  • 78.
    Arrays : Initializationwithout Size Example : 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. www.opengurukul.com 78
  • 79.
    Arrays : Example Program: #include<stdio.h> Output: #define MAX_CLASS 5 students in class 1 : 30 Int 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]); www.opengurukul.com 79 }
  • 80.
    Arrays : MultidimensionalArray Often 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]; www.opengurukul.com 80
  • 81.
    Arrays : MultidimensionalArray : Example Program: 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; } www.opengurukul.com // for printing all the values of the array 81
  • 82.
    Arrays : Arrayas Parameters 1.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. www.opengurukul.com 82
  • 83.
    Arrays : Arrayas Parameter : Example PROGRAM: 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 4 int main() { int toppers_roll_no[NUM_TOPPERS] = {10, 20, 30,432}; print_students(toppers_roll_no, NUM_TOPPERS); return 0; } www.opengurukul.com 83
  • 84.
    C Programming Module :Structure www.opengurukul.com 84
  • 85.
    Basics of Structures Astructure 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 ; www.opengurukul.com 85 The keyword "struct" is followed by a structure name.
  • 86.
    Structures : AccessMembers/Fields emp_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.member Example e.id e.emp_name www.opengurukul.com 86
  • 87.
    Structures : Example /*Example : struct.c */ Output : #include <stdio.h> #include <string.h> $ gcc -o struct struct.c typedef 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); www.opengurukul.com 87 }
  • 88.
    Pointers to Structure Thepointer 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_name Example: emp_t *e_p; /* pointer to struct */ e_p->emp_id e_p->emp_name www.opengurukul.com 88
  • 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); } www.opengurukul.com 89
  • 90.
    Self-referential Structure A structuremay 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 structures struct node { int value; struct node *next; }; www.opengurukul.com 90
  • 91.
    C Programming Pointers www.opengurukul.com 91
  • 92.
    Pointers : Introduction Definition-Apointer 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 www.opengurukul.com 92
  • 93.
    Pointers : Needof Pointers These 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. www.opengurukul.com 93
  • 94.
    Pointers : Declaration& Initialization : Example Program: #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 x printf(“ p = %un”,p); // the address of x printf(“&p = %un”, &p); // the address of the pointer } www.opengurukul.com 94
  • 95.
    Pointers : ArithmeticOperation Pointer 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. www.opengurukul.com 95
  • 96.
    Address Arithmetic Example Program: #include<stdio.h> Output: void main() a = 30, b = 6 { x = 30 int 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); www.opengurukul.com 96 }
  • 97.
    Pointers : Characterpointers in C In 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 0 cp = “matsya”; cp www.opengurukul.com 97
  • 98.
    Pointers : Charpointer : Example Program: Output: #include<stdio.h> Mataya void main() { char *cptr; cptr=“Matsya”; printf(“%s”,cptr); while(*cptr!=‘0’) { if(*cptr==‘s’) *cptr=‘a’; printf(“%c”,*cptr); cptr++; } } www.opengurukul.com 98
  • 99.
    Pointers : Pointersto Arrays Pointer 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 www.opengurukul.com 99
  • 100.
    Pointers : Pointersto Array : Example Program : Output: # include<stdio.h> a[0] = 1 void main() p+0 = 1 { a[1] = 23 int a[]={1,23,45}; p+1 = 23 int *p, i; p=&a[0]; a[2] = 45 for(i=0;i<3;i++) p+2 = 45 { printf("a[%d] = %dn",i,a[i]); printf("p+%d=%dn",i,*(p+i)); } } www.opengurukul.com 100
  • 101.
    Pointers : Commandline arguments main() function has two arguments. The first is number of command line arguments i.e., int argc The second is a pointer to an array of character strings that contain the arguments one per string i.e., char *argv[] www.opengurukul.com 101
  • 102.
    Command line Argument: Example Program: cmd.c bin>tcc cmd.c #include<stdio.h> bin>cmd.exe this is a program main(int argc, char *argv[]) Output: { this is a program int i; for(i=1;i<argc;i++) { printf(“%8s”,argv[i]); } } www.opengurukul.com 102
  • 103.
    C Programming Input &Output www.opengurukul.com 103
  • 104.
    IO : Fileinput & output The 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.h The standard library functions for file input and output are included in the c standard library header <stdio.h> Type We 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. Functions Reading from or writing to a file in C requires 3 basic steps: Open the file. Do reading/writing. www.opengurukul.com 104 Close the file.
  • 105.
    Opening a fileusing fopen A filepointer is used to open a file present using the format, FILE* fp; FILE* fopen(char *name, char *mode); For opening a file fp = fopen(name of file, mode); Mode Normal Access r Open existing file for "r"eading w Open file for "w"riting, destroying the contents; create if necessary a "A"ppend at end of file; create if necessary Update Access (for fixed-length records) r+ Open existing file for "r"eading & writing w+ Open file for reading & "w"riting, destroying the contents; create if necessary a+ Open file for reading & writing -- all writing is "a"ppended to the end of the file; create if necessary www.opengurukul.com 105
  • 106.
    Opening a fileusing fopen For checking whether a file exists give fopen(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 file int 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. www.opengurukul.com 106
  • 107.
    Opening a fileusing fopen getchar 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 used. int 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. www.opengurukul.com 107
  • 108.
    Opening a fileusing 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"); www.opengurukul.com 108
  • 109.
    Line I/O fgets char *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. fputs int 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. www.opengurukul.com 109
  • 110.
    Formatted Output usingprintf The output function printf translates internal values to characters. For example int 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. www.opengurukul.com 110
  • 111.
    Formatted Output usingprintf u 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 d's is given by the recision e,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 www.opengurukul.com % no argument is converted; print a % 111
  • 112.
    Formatted Output usingprintf A 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 effects The 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: www.opengurukul.com 112 :%-15.10s: :hello,wor :
  • 113.
    Formatted Input usingscanf scanf 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 Conversions Character | Input Data | Argument Type d | decimal integer | int * u | unsigned decimal integer | unsigned int * www.opengurukul.com 113 c | character | char *
  • 114.
    Formatted Input usingscanf s | 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 www.opengurukul.com 114
  • 115.
    Error Handling stderr The secondoutput 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. exit The 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 www.opengurukul.com uses this one as a sub process. 115
  • 116.
    Char I/O fgetc() int fgetc(FILE*fp); The fgetc function is used to read a character from a stream If successful, fgetc returns the next byte or character from the stream If unsuccessful, fgetc returns EOF. getc() macro behaves similar to fgetc() it may evaluate its arguments more than once. getchar() int getchar(void); function takes no argument. www.opengurukul.com 116 equivalent to getc(stdin).
  • 117.
    Char I/O fputc() int fputc(intc, FILE *stream); The fputc function is used to write a character from a stream to the file If successful, fputc writes the next byte or character from the stream If unsuccessful, fgetc returns EOF. www.opengurukul.com 117
  • 118.
    C Programming Module :Strings www.opengurukul.com 118
  • 119.
    Strings Strings are definedas an array of characters. We can used following statement to define a string of 5 characters char 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] */ www.opengurukul.com 119
  • 120.
    String Literals A stringthat 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 www.opengurukul.com 120
  • 121.
    String Terminator A specialcharacter '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 www.opengurukul.com 121
  • 122.
    String format specifier Wemust 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); www.opengurukul.com 122 }
  • 123.
    string length :strlen function The function strlen() can be used to Example: Calculate lengh of string calculate the length of the string. literals "Hello World" It doesn't 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 www.opengurukul.com of Hello World = 11 123
  • 124.
    string copy :strcpy function We 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 www.opengurukul.com 124
  • 125.
    string concatenation :strcat function We 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 www.opengurukul.com 125
  • 126.
    string compare :strcmp function We 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); www.opengurukul.com 126
  • 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 www.opengurukul.com 127
  • 128.
    search for stringin string : strstr The 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); www.opengurukul.com 128
  • 129.
    C Programming Storage Classes www.opengurukul.com 129
  • 130.
    Scope of Variables Acomplete 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 shouldwww.opengurukul.com be defined in any one source file 130
  • 131.
    External Variables The programcan 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. www.opengurukul.com 131
  • 132.
    External Variables:Example Header File: common.h Second Source File : second.c extern 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, www.opengurukul.com ev = 5 132
  • 133.
    Static Variables Static storageclass 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. www.opengurukul.com 133
  • 134.
    Static Variables :Example PROGRAM: OUTPUT : #include <stdio.h> 2 #include <stdlib.h> 3 void add() { 4 static int x = 1; x++; printf("%dn", x); } main() { add(); // return 2 add(); // return 3 add(); // return 4 } www.opengurukul.com 134
  • 135.
    Storage Classes :Register Variables The 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; www.opengurukul.com 135
  • 136.
    D e fa 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 0 re g is te r b od y b od y G a rb a g e v a lu e www.opengurukul.com 136
  • 137.
    Storage Classes :Initialization The static and extern variables are initialized to 0 by compiler An automatic variable remains uninitialized and it will contain garbage. You can initialize a variable while defining it. www.opengurukul.com 137
  • 138.
    Storage Classes :Initialization : Example extern 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); } www.opengurukul.com 138
  • 139.
    C Programming Module Miscellaneous www.opengurukul.com 139
  • 140.
    The typedef The typedefstatement 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 */ www.opengurukul.com 140
  • 141.
    Union A union isa 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; }; www.opengurukul.com 141
  • 142.
    Union:Access union-name.member : accessunion fields using union variable union-pointer->member : access union fields using pointer to union variable Example: www.opengurukul.com 142
  • 143.
    Bit-fields When Storage spaceis 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 04 or 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. www.opengurukul.com 143
  • 144.
    Bit-fields Certain idioms appearfrequently: 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).... is 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. www.opengurukul.com 144