INTRODUCTION TO C PROGRAMMING

71,034 views
72,221 views

Published on

This C tutorial covers every topic in C with the programming exercises. This is the most extensive tutorial on C you will get your hands on. I hope you will love the presentation. All the best. Happy learning.
Feedbacks are most welcome. Send your feedbacks to dwivedi.2512@gmail.com. You can download this document in PDF format from the link, http://www.slideshare.net/dwivedi2512/learning-c-an-extensive-guide-to-learn-the-c-language

Published in: Education, Technology
61 Comments
260 Likes
Statistics
Notes
No Downloads
Views
Total views
71,034
On SlideShare
0
From Embeds
0
Number of Embeds
5,555
Actions
Shares
0
Downloads
2,995
Comments
61
Likes
260
Embeds 0
No embeds

No notes for slide
  • `
  • INTRODUCTION TO C PROGRAMMING

    1. 1. LEARNING ABHISHEK DWIVEDI IT DEPARTMENT AVIT, CHENNAI. ABHISHEK DWIVEDI 3 July 2010
    2. 2. WHICH TOPIC U WANNA STUDY ??? INTRODUCTION CONSTANTS & VARIABLES OPERATORS & EXPRESSIONS STRUCTURE OF A C PROGRAM CONTROL STRUCTURES ARRAYS AND STRINGS FUNCTIONS STORAGE CLASSES STRUCTURES & UNIONS POINTERS DYNAMIC MEMORY ALLOCATION FILE MANAGEMENT IN C COMMAND LINE ARGUMENTS ABHISHEK DWIVEDI 3 July 2010
    3. 3. Introducing C  C is a programming language developed at AT & T Bell Laboratories of USA in 1972, designed and written by “Dennis Ritchie”.  C is highly portable i.e., software written for one computer can be run on another computer.  An important feature of ‘C’ is its ability to extend itself. A C program is basically a collection of functions. ABHISHEK DWIVEDI 3 July 2010
    4. 4. Historical Development of C ALGOL  Algorithmic Language CPL  Combined Programming Language BCPL  Basic Combined Programming Language ABHISHEK DWIVEDI 3 July 2010
    5. 5. C Tokens  A token is an atomic unit (smallest indivisible units) in a program.  The most basic elements in a C program recognized by the compiler are a single character or a group of characters called C tokens.  The compiler cannot breakdown the token any further. For example, the words main, ‘{‘ (brace), ‘(‘ (parenthesis) are all tokens of C program. ABHISHEK DWIVEDI 3 July 2010
    6. 6. Types of tokens. 1. Keywords Examples: float, int, double, while, for. 2. Identifiers Examples: main, amount 3. Constants Examples: 12.4, 7894 4. Strings Examples: “CSM”, “Thursday” 5. Special Symbols Examples: [,], {, }, (, ) 6. Operators Examples: +, *, / ABHISHEK DWIVEDI 3 July 2010
    7. 7. The C character set The C character set includes the upper case letters A to Z, the lower case a to z, the decimal digits 0 to 9 and certain special characters. Letters a, b, c, ……………z Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 Special characters ~,.;:?‘“!()[]{}/<>=+ -$#@&*%^ ABHISHEK DWIVEDI 3 July 2010
    8. 8. Character/ Meaning Character/ Meaning Symbol Symbol ~ tilde , Comma . Period ; Semicolon ? Ques. mark : Colon “ Double Quote ‘ Single Quote ( Left parenthesis ) Right Parenthesis [ Left Bracket ] Right Bracket { Left Brace } Right Brace / Slash Back Slash < Less than > Greater than = Equal to ! Exclamatory Mark - Minus + Plus # Hash $ Dolor Sign & Ampersand * Asterisk (or star) % Percent ^ Carat _ Underscore | Vertical Bar ABHISHEK DWIVEDI 3 July 2010
    9. 9. Identifiers Identifiers are distinct names given to program elements such as constants, variables, etc. An Identifier is a sequence of letters, digits, and the special character ‘_’ (underscore). 1. It must start with either a letter or underscore. ‘_’ 2. No commas or blanks are allowed within a variable name. 3. The upper case and lower case letters are treated as distinct, i.e., identifiers are case-sensitive. 4. An identifier can be of any length. 5. No special symbol can be used in a variable name. ABHISHEK DWIVEDI 3 July 2010
    10. 10. Keywords  Keywords are predefined tokens in C. These are also called reserved words.  Key words have special meaning to the C compiler. These key words can be used only for their intended action; they cannot be used for any other purpose.  C has 32 keywords. ABHISHEK DWIVEDI 3 July 2010
    11. 11. The standard keywords are auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while ABHISHEK DWIVEDI 3 July 2010
    12. 12. Data types A data type defines a set of values and the operations that can be performed on them. Every datatype item (constant, variable etc.) in a C program has a datatype associated with it. C also has a special datatype called void, which, indicates that any data type, i.e., no data type, does not describe the data items. ABHISHEK DWIVEDI 3 July 2010
    13. 13. Size (No. of Data types Description Range Bytes) Char Single character 1 0 to 255 Int An integer 2 -32768 to +32767 Float Floating point number 4 -2,147,483,648 to +2,147,483,647 Double Floating point number 8 Approximately 15 digits of Precision Void No data type 0 signed char Character 1 -128 to 127 unsigned char Unsigned character 1 0 to 255 short signed int Short signed integer 2 -32768 to +32767 short unsigned int Short unsigned integer 3 0 to 65535 Long singed int Long signed integer 4 -2,147,483,648 to +2,147,483,647 ABHISHEK DWIVEDI 3 July 2010
    14. 14. Constants and Variables A constant is a literal, which remain unchanged during the execution of a program. A constant is a fixed value that cannot be altered during the execution of a program. C constants can be classified into two categories.  Primary Constants  Secondary Constants ABHISHEK DWIVEDI 3 July 2010
    15. 15. Rules for constructing Integer constants An integer constant must have at least one digit. It should not contain either a decimal point or exponent. If a constant is positive, it may or may not be preceded by a plus sign. If it is a negative, it must be preceded by a minus sign. Commas, blanks and non-digit characters are not allowed in integer constants. The value of integer constant cannot exceed specified limits. The valid range is –32768 to +32767. ABHISHEK DWIVEDI 3 July 2010
    16. 16. Real constants Real values are often called floating-point constants. There are two ways to represent a real constant decimal form and exponential form. In exponential form of representation, the real constant is represented in two parts. The part appearing before ‘e’ is called mantissa, whereas the part following ‘e’ is called exponent. ABHISHEK DWIVEDI 3 July 2010
    17. 17. Rules for constructing Real constants The mantissa part and the exponential part should be separated by a letter e. The mantissa part may have a positive or negative sign. Default sign of mantissa part is positive. The exponent must have at least one digit, which must be a positive or negative integer. Default sign is positive. Range of real constants expressed in exponential form is - 3.4e38 to 3.4e38. ABHISHEK DWIVEDI 3 July 2010
    18. 18. Rules for constructing Characters constants A character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. Both the inverted commas point to the left. For example, ‘A’ is valid character constant whereas A is not. The maximum length of a character constant can be 1 character. Note: Every character has its ASCII (American Standard Code for Information Interchange) value. That means every character is interchange with integer constant. For example, ‘A’ value is 65 and ‘a’ value is 97. ABHISHEK DWIVEDI 3 July 2010
    19. 19. String constants A string constant is a sequence of characters enclosed in double quotes. The characters may be letters, numbers, blank space or special characters. Note that “” is null string or empty string. And the single string constant “A” is not equivalent to the single character constant ‘A’. Each string constant must end with a special character ‘0’. This character is called null character and used to terminate the string. The compiler automatically places a null ‘0’ character at the end of every string constant. ABHISHEK DWIVEDI 3 July 2010
    20. 20. Escape sequence Some non-printing characters and some other characters such as double quote (“), single quote (‘), question mark (?) and backslash (), require an escape sequence. A list of commonly used backslash character constants is given below. Escape Escape Meaning ASCII value Meaning ASCII value Sequence Sequence a Bell 7 r Carriage 13 return b Back Space 8 ” Double Quote 34 t Tab 9 ’ Single Quote 39 n New line 10 ? Question 63 Mark v Vertical tab 11 Back Slash 92 f Form feed 12 0 Null 0 ABHISHEK DWIVEDI 3 July 2010
    21. 21. Variables A variable can be considered as a name given to the location in memory. The term variable is used to denote any value that is referred to a name instead of explicit value. A variable is able to hold different values during execution of a program, where as a constant is restricted to just one value. For example, in the equation 2x + 3y = 10; since x and y can change, they are variables, whereas 2,3 and 10 cannot change, hence they are constants. The total equation is known as expression. ABHISHEK DWIVEDI 3 July 2010
    22. 22. Rules for constructing variable names The name of a variable is composed of one to several characters, the first of which must be a letter . No special characters other than letters, digits, and underscore can be used in variable name. Some compilers permit underscore as the first character. Commas or Blanks are not allowed with in a variable name. Upper case and Lower case letters are significant. That is the variable “income” is not same as “INCOME”. The variable name should not be a C key word. Also it should not have the same name as a function that is written either by user or already exist in the C library. ABHISHEK DWIVEDI 3 July 2010
    23. 23. C Instructions There are basically four types of instructions in C: Type Declaration Instruction Input/Output Instruction Arithmetic Instruction Control Instruction ABHISHEK DWIVEDI 3 July 2010
    24. 24. The purpose of each instructions  Type Declaration to declare the type of instruction variables used in a C program  Input/Output instruction To perform the function of supplying input data to a program and obtaining the output results from it.  Arithmetic instruction to perform arithmetic operations between constants and variables.  Control instruction to control the sequence of execution of various statements in a C program. ABHISHEK DWIVEDI 3 July 2010
    25. 25. Operators & Expressions An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in program to manipulate data and variables. The data items that operators act upon are called operands. Some operators require two operands, while others act upon only one operand. The operators are classified into unary, binary and ternary depending on whether they operate on one, two or three operands respectively. ABHISHEK DWIVEDI 3 July 2010
    26. 26. Types of operators C has four classes of operators 1. Arithmetic Operators 2. Relational Operators 3. Logical Operators 4. Bit-wise Operators In addition, C has some special operators, which are unique to C, they are 1. Increment & Decrement Operators 2. Conditional Operators 3. Assignment Operators, etc. ABHISHEK DWIVEDI 3 July 2010
    27. 27. Arithmetic Operators There are five arithmetic operators in C. The following table lists the arithmetic operators allowed in C: Operator Meaning + Addition _ Subtraction; also for unary minus * Multiplication / Division % Modulo division (remainder after integer division) ABHISHEK DWIVEDI 3 July 2010
    28. 28. Relational Operators Relational Operators are symbols that are used to test the relationship between two variables or between a variable and a constant. We often compare two quantities, and depending on their relation takes certain decisions. These comparisons can be done with the help of relational operators. C has six relational operators as shown below. Operator Meaning > Greater than >= Greater than or Equal to < Less than <= Less than or Equal to == Equal to != Not equal to ABHISHEK DWIVEDI 3 July 2010
    29. 29. Logical Operators Logical Operators are symbols that are used to combine or negate expressions containing relational operators. C has three logical operators as defined below. Operator Meaning && Logical AND || Logical OR ! Logical NOT ABHISHEK DWIVEDI 3 July 2010
    30. 30. Bitwise operators The lowest logical element in the memory is bit. C allows the programmer to interact directly with the hardware of a particular system through bitwise operators and expression. These operators work only with int and char datatypes and cannot be used with float and double type. The following table shows the bitwise operators that are available in C. Operator Meaning - One’s Complement | Bitwise OR & Bitwise AND ^ Bitwise Exclusive OR (XOR) >> Right Shift << Left Shift ABHISHEK DWIVEDI 3 July 2010
    31. 31. Increment & Decrement operators C has two very useful operators for adding and subtracting a variable. These are the increment and decrement operators, ++ and -- . These two operators are unary operators. The increment operator ++ adds 1 to its operand, and the decrement operator -- subtracts 1 from its operand. Therefore, the following are equivalent operations. ++i is equivalent to i = i + 1; --i is equivalent to i = i – 1; These operators are very useful in loops. ABHISHEK DWIVEDI 3 July 2010
    32. 32. Assignment operators In addition to usual assignment operator =, C has a set of shorthand operators, that simplifies the coding of a certain type of assignment statement. It is of the form var op = exp where var is a variable, op is a C binary arithmetic operator and exp is an expression. Statement Equivalent Statement a+=b a=a+b a-=b a=a-b a * =b a=a*b a*=b+c a = a * ( b+ c) a%=b a=a%b a*=a a=a*a ABHISHEK DWIVEDI 3 July 2010
    33. 33. Conditional Operator C provides a peculiar operator ? : which is useful in reducing the code. It is ternary operator requiring three operands. The general format is exp1 ? exp2 : exp3; where exp1, exp2 and exp3 are expressions. In the above conditional expression, exp1 is evaluated first. If the value of exp1 is non zero (true), then the value returned will be exp2. if the value of exp1 is zero (false), then the value returned will be exp3. ABHISHEK DWIVEDI 3 July 2010
    34. 34. Hierarchy (precedence) of operators The priority or precedence in which the operations of an arithmetic statement are performed is called the hierarchy of operators. The operators of at the higher level of precedence are evaluated first. The operators of the same precedence are evaluated either from left to right or from right to left, depending on the level. This is known as the Associativity property of an operator. PRECEDENCE OF OPERATORS (Arithmetic operators only) Operator Description Associativity Rank * Multiplication Left to right 3 / Division “ 3 % Modulo “ 3 + Addition “ 4 - Subtraction “ 4 ABHISHEK DWIVEDI 3 July 2010
    35. 35. Structure of a ‘C’ program C programs consist of one or more functions. Each function performs a specific task. A function is a group or sequence of C statements that are executed together. The following is a simple C program that prints a message on the screen. /* A simple program for printing a message */ # include <stdio.h> # include <conio.h> void main( ) { clrscr( ); printf(“Welcome to C”); getch( ); } ABHISHEK DWIVEDI 3 July 2010
    36. 36. Description The first line /* A simple program for printing a message */ is a comment line. Comments in the c program are optional and may appear anywhere in a C program. Comments are enclosed between /* and */. The second line # include <stdio.h> tells the compiler to read the file stdio.h and include its contents in this file. stdio.h, one of header files, contain the information about input and output functions. stdio.h means Standard Input Output Header file. This file contains the information about printf() function. ABHISHEK DWIVEDI 3 July 2010
    37. 37. Description (contd…) The third line # include <conio.h> tells the compiler to read the file conio.h and include its contents in this file. conio.h means Consoled Input Output Header file. This file contains the information about clrscr() and getch() functions. The fourth line void main( ) is the stat of the main program. The word main is followed by a pair of ordinary parenthesis ( ), which indicates that main is also a function. The fifth line { the left brace represents the beginning of the program. The sixth line clrscr( ); tells the compiler to clear the screen and kept the cursor at left side corner. ABHISHEK DWIVEDI 3 July 2010
    38. 38. Description (contd…) The seventh line printf( “Welcome to C”); this function causes its arguments to be printed on the screen on the computer. The eight line getch( ); is reads the single character directly from the keyboard without printing on the screen. The ninth line } the right brace represents the ending of the program. ABHISHEK DWIVEDI 3 July 2010
    39. 39. Rules to write a C program 1. All C statements must end with semicolon. 2. C is case-sensitive. That is, upper case and lower case characters are different. Generally the statements are typed in lower case. 3. A C statement can be written in one line or it can split into multiple lines. 4. Braces must always match upon pairs, i.e., every opening brace { must have a matching closing brace }. 5. Every C program starts with void main( ) function. 6. Comments cannot be nested. For example, /* Welcome to ‘C’ ,/* programming*/ */ A comment can be split into more than one line. ABHISHEK DWIVEDI 3 July 2010
    40. 40. Execution of C Program Steps to be followed in writing and running a C program. Creation of Source Program Create a C program file in various C compilers are available under MS-DOS, Turbo C Editor etc. Compilation of the Program Turbo C compiler is user friendly and provides integrated program development environment. Thus, selecting key combination can do compilation. That means press Alt + F9 for compilation. Program Execution In Turbo C environment, the RUN option will do the compilation and execution of a program. Press Ctrl + F9 for execution the program. ABHISHEK DWIVEDI 3 July 2010
    41. 41. printf( ) Function: Writing Output Data The printf( ) function is used to write information to standard output (normally monitor screen). The structure of this function is printf(format string, list of arguments); The format string contains the following: 1. Characters that are simply printed on the screen. 2. Specifications that begin with a % sign and define the output format for display of each item. 3. Escape sequence characters that begin with a sign such as n, t, b etc. Character Argument Resulting Output c Character A single character d Integer Signed decimal integer s String Prints character strings f Floating Single floating point number point ABHISHEK DWIVEDI 3 July 2010
    42. 42. scanf( ) Function: getting user input The real power of a technical C program is its ability to interact with the program user. This means that the program gets input values for variables from users. The scanf( ) function is a built-in C function that allows a program to get user input from the keyboard. The structure of this function is scanf(format string &list of arguments); Examples scanf(“%d”, &a ); scanf(“%d %c %f ”,&a, &b, &c ); ABHISHEK DWIVEDI 3 July 2010
    43. 43. CONTROL STRUCTURES The control flow statements of a language determine the order in which the statements are executed. We also need to be able to specify that a statement, or a group of statements, is to be carried out conditionally, only if some condition is true. Also we need to be able to carry out a statement or a group of statements repeatedly based on certain conditions. These kinds of situations are described in C using Conditional Control and Loop Control structures. ABHISHEK DWIVEDI 3 July 2010
    44. 44. Conditional & loop structures A conditional structure can be implemented in C using The if statement The if-else statement The nested if-else statement The switch statement. whereas loop control structures can be implemented in C using while loop do-while loop for statement ABHISHEK DWIVEDI 3 July 2010
    45. 45. The if statement The if statement is used to control the flow of execution of statements. The general form of if statement is if (condition) statement; Suppose if it is required to include more than one statement, then a compound statement is used, in place of single statement. The form of compound statement is if (condition) { statement1; statement2; } If the condition is true, then the statement/statements will be executed. If the condition is false, then the statement/statements will not be executed. ABHISHEK DWIVEDI 3 July 2010
    46. 46. The if statement : Program Program /* Inputting year is Leap or not */ #include<stdio.h> #include<conio.h> void main() Output 1 { Enter year:1990 int year; Not leap year clrscr(); Output 2 printf(“Enter year:”); Enter year:1996 Leap year scanf(“%d”,&year); if(year%4==0) printf(“Leap year”); if(year%4!=0) printf(“Not leap year”); getch(); } ABHISHEK DWIVEDI 3 July 2010
    47. 47. The if-else Statement The general form of if-else statement is… if (condition) statement1; else statement2; If the condition is true, then statement1 is executed. Otherwise if the condition is false, then the statement2 is executed. Here statements statement1 and statement2 are either simple statements or compound statements. That is… if (condtion) { statements /* if block */ } else { statements /* else */ } ABHISHEK DWIVEDI 3 July 2010
    48. 48. The if-else Statement : Program Program /* Single digit or not */ #include<stdio.h> #include<conio.h> void main() { Output 1 Enter a number:5 int n; Single digit clrscr(); Output 2 printf(“Enter a number:”); Enter a number:12 scanf(“%d”,&n); Not single digit if(n<=9) printf(“Single digit”); else printf(“Not single digit”); getch(); } ABHISHEK DWIVEDI 3 July 2010
    49. 49. Nested if-else Statements When a series of conditions are involved, we can use more than one if-else statement in nested form. This form is also known as if-else if-else statements. The general form of if-else if-else statement is if (condition) statements; else if (condition) statements; else statements; Note that a program contains number of else if statements and must be ended with else statement. ABHISHEK DWIVEDI 3 July 2010
    50. 50. Nested if-else Statements : Program Program /* To check whether +ve, -ve or zero */ #include<stdio.h> #include<conio.h> void main() { Output 1 int n; Enter a number: -2 clrscr(); -ve printf(“Enter a number:”); Output 2 scanf(“%d”,&n); Enter a number:0 If(n>0) zero printf(“+ve”); Output 3 else if(n<0) Enter a number:5 printf(“-ve”); +ve else printf(“zero”); getch(); } ABHISHEK DWIVEDI 3 July 2010
    51. 51. The Switch Statement The Switch statement is an extension of the if-else if-else statement. The switch makes one selection when there are several choices to be made. The direction of the branch taken by the switch statement is based on the value of any int (or int compatible) variable or expression. The general form of Switch statement is shown below. switch (variable) { case constant1:statement 1; case constant2:statement 2; case constant3:statement 3; “ “ “ “ “ “ “ “ “ case constant n:statement n; default :statement; } ABHISHEK DWIVEDI 3 July 2010
    52. 52. The Switch Statement : Program Program /* Letter -> color name */ #include<stdio.h> #include<conio.h> void main() Output 1 { char x; Enter a char:w clrscr(); w->white printf(“Enter a char:”); Output 2 scanf(“%c”,&x); Enter a char:b switch(x) b->black { Output 3 case ‘w’:printf(“w->white”); Enter a char:c break; No color case ‘b’:printf(“b->black”); break; default:printf(“No color”); } getch(); } ABHISHEK DWIVEDI 3 July 2010
    53. 53. The exit( ) Function The exit( ) is a function in the standard library of C. This function causes immediate termination of the program and execution control return to the operating system. In general, the termination to exit( ) function is 0 to indicate that termination is normal. Other arguments may be used to indicate some sort of an error. ABHISHEK DWIVEDI 3 July 2010
    54. 54. LOOPS A portion of program that is executed repeatedly is called a loop. The C programming language contains three different program statements for program looping. They are  For loop  While loop  Do-While loop ABHISHEK DWIVEDI 3 July 2010
    55. 55. The For Loop The for loop is used to repeat the execution statement for some fixed number of times. The general form of for loop is for(initialization;condition;increment/decrement) statement; where the statement is single or compound statement. initialization is the initialization expression, usually an assignment to the loop-control variable. This is performed once before the loop actually begins execution. condition is the test expression, which evaluated before each iteration of the loop, which determines when the loop will exist. increment is the modifier expression, which changes the value of loop control variable. This expression is executed at the end of each loop. ABHISHEK DWIVEDI 3 July 2010
    56. 56. The For Loop : Program Program /* Print 1 to 10 numbers */ #include<stdio.h> Output #include<conio.h> 1 void main() 2 3 { 4 int i; 5 clrscr(); 6 7 for(i=1;i<=10;i++) 8 printf(“n%d”,i); 9 getch(); 10 } ABHISHEK DWIVEDI 3 July 2010
    57. 57. The While Loop The while loop is best suited to repeat a statement or a set of statements as long as some condition is satisfied. The general form of while loop is initial expression; while(conditional-expression) { statement; increment/decrement; } where the statement (body of the loop) may be a single statement or a compound statements. The expression (test condition) must results zero or non-zero. ABHISHEK DWIVEDI 3 July 2010
    58. 58. The While Loop : Program Program /* Print a message 3 times */ #include<stdio.h> #include<conio.h> void main() Output { Jiffy Solutions int i=1; Jiffy Solutions clrscr(); Jiffy Solutions while(i<=3) { printf(“nJiffy Solutions”); i++; } getch(); } ABHISHEK DWIVEDI 3 July 2010
    59. 59. The do-while loop The structure of do-while loop is similar to while loop. The difference is that in case of do-while loop the expression is evaluated after the body of loop is executed. In case of while loop the expression is evaluated before executing body of loop. The general form of do-while statement is do { statement; }while(expression); where statement is a single statement or compound statement. In contrast to while loop statement (body of loop), do-while loop is executed one or more times. ABHISHEK DWIVEDI 3 July 2010
    60. 60. ARRAYS An Array is a collection of same data type. The elements of an array are referred by a common name and are differentiate from one another by their position with in an array. The elements of an array can be of any data type but all elements in an array must be of the same type. The general form of declaring a array is type array_name[size]; where type is a valid datatype, array_name is the name of the array and size is the number of elements that array_name contains. Example: int A[100]; int  data type of elements that an array A  name of array 100  size of an array ABHISHEK DWIVEDI 3 July 2010
    61. 61. ARRAYS (Contd…) The individual elements of an array can be referenced by means of its subscript (or index) Suppose A is an array of 20 elements, we can reference each element as A[0]  1st element A[1]  2nd element A[2]  3rd element : : A[19]  20th element Note: Subscript enclosed within parenthesis. In C subscript starts from 0. That is, if we declare an array of size n, then we can refer the elements from 0 to (n-1)th element. Arrays are of 3 types. They are Single Dimensional Array Double Dimensional Array Multi Dimensional Array ABHISHEK DWIVEDI 3 July 2010
    62. 62. Single Dimensional Array The general form of Single Dimensional array is: datatype variable[size]; Example: int A[20]; Initialization of arrays during declaration Similar to other datatypes, the array also can be initialized at the time of declaration. int num[5] ={3,2,1,5,4}; char name[15] = {‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’,’s’}; float rate[] = {20.5,15.75,12.34}; ABHISHEK DWIVEDI 3 July 2010
    63. 63. Single Dimensional Array : Program Program illustrating Single Dimensional Array #include<stdio.h> #include<conio.h> void main() { int a[5],i; clrscr(); printf(“Enter 5 elements into an array:”); for(i=0;i<=4;i++) scanf(“%d”,&a[i]); printf(“The 5 elements are:”); for(i=0;i<=4;i++) printf(“n%d”,a[i]); getch(); } ABHISHEK DWIVEDI 3 July 2010
    64. 64. Two-Dimensional Array The general form of Two-Dimensional Arrays is type array_name[row_size][column_size]; Example: int a[2][2]; Initializing Two-Dimensional Arrays Like the one-dimensional arrays, following their declaration with a list of initial values enclosed in braces may initialize two-dimensional arrays. For example, int a[2][2] ={1,2,5,4}; initializes the elements of the first row to zero and the second row to one. The initialization is done row by row. The above statement can be equivalently written as int a[2][2]={{1,2},{5,4}}; ABHISHEK DWIVEDI 3 July 2010
    65. 65. Two-Dimensional Array : Programs Program Illustrating Two Dimensional arrray printf(“The 4 elements are:n”); #include<stdio.h> for(i=0;i<=1;i++) #include<conio.h> { void main() for(j=0;j<=1;j++) { { printf(“%d ”,a[i][j]); int a[2][2],i,j; } clrscr(); printf(“n”); printf(“Enter 4 elements into array:”); } for(i=0;i<=1;i++) getch(); } { for(j=0;j<=1;j++) { scanf(“%d”,&a[i][j]); } } ABHISHEK DWIVEDI 3 July 2010
    66. 66. Handling of Character Strings A string is an array of characters. There is no string built-in data type in C. But we can declare string as an array of characters. To recognize a character array, it should end with a null character (‘0’). For example, the string SCIENCE would be stored as ‘S’ ‘C’ ‘I’ ‘E’ ‘N’ ‘C’ ‘E’ ‘0’ The length of a string is the number of characters it contains excluding null character. Hence, the number of locations needed to store a string is one more than length of string. In this example, the length of the string is 7. ABHISHEK DWIVEDI 3 July 2010
    67. 67. Declaring and initializing string variables The general form of declaration of string variable is char string-name[size]; where, string-name is the name of a string and size is the maximum number of characters the string-name can contain. Example: char name[30]; String variables can be initialized at the time of declaration. Example: char name[30] = “Millennium”; A string can also be initialized at the time of declaration in the following ways. char name[30] = “Millennium”; or char name[30] ={‘M’,’i’,’l’,’l’,’n’,’n’,’i’,’u’,’m’,’0’}; ABHISHEK DWIVEDI 3 July 2010
    68. 68. Reading and writing strings The scanf(), printf() function is used with %s with format specification to read and print a string. Example: char str[30]; scanf(“%s”,str); printf(“%s”,str); In the case of reading strings, the ampersand (&) is not required before the string variable name. As mentioned earlier, one of the limitations of the scanf() function is that it is not capable of holding multiword strings, even though it can read them. ABHISHEK DWIVEDI 3 July 2010
    69. 69. Reading and writing strings : Program Program #include<stdio.h> #include<conio.h> void main() { char line[80]; clrscr(); printf(“Enter a linen”); scanf(“%s”,line); printf(“The entered line is:%s”,line); getch(); } ABHISHEK DWIVEDI 3 July 2010
    70. 70. String handling Functions: string.h Every C compiler provides a large set of string handling library functions, which are contained in the header file string.h The following table shows some of the functions available in string.h header file. Function Meaning strcat() String concatenate. Append one string to another. First character of string2 overwrites null character of string1. strlen() Returns the length of the string not counting the null character. strlwr() Converts a string to lower case. strupr() Converts a string to upper case. strcpy() Copies a string into another. strcmp() Compares two strings strrev() Reverses a string ABHISHEK DWIVEDI 3 July 2010
    71. 71. strcat() function The strcat() function concatenates the source string at the end of the target string. For example “Computing” and “Techniques” on concatenation would result in string “ComputingTechniques”. The general form is strcat(string1, string2); strong2 appends to string1 and the first character to string2 overwrites null character of first string1. This function returns the first argument i.e., string1. The string2 remains unchanged. ABHISHEK DWIVEDI 3 July 2010
    72. 72. strcat() function : Program Program #include<stdio.h> #include<conio.h> #include<string.h> void main() Output Enter String1:Jiffy { Enter String2:Solutions char s1[30],s2[15]; The entire string is: clrscr(); Jiffy Solutions printf(“Enter String1:”); gets(s1); printf(“Enter String2:”); gets(s2); printf(“The entire string is:%s”,strcat(s1,s2)); getch(); } ABHISHEK DWIVEDI 3 July 2010
    73. 73. strcmp() function strcmp() function compares two strings to find out whether they are same or different. The two strings are compared character by character until there is a mismatch or end of one of the strings is reached, whichever occurs first. The general form is: strcmp(string1, string2); If the two strings are same, strcmp() returns a value 0. If they are not same, it returns the numeric difference between the ASCII values of the first non-matching characters. That is, it returns less than 0 if string1 is less than string2, and greater than 0 if string1 is greater than string2. ABHISHEK DWIVEDI 3 July 2010
    74. 74. strcmp() function : Program Program #include<stdio.h> #include<conio.h> #include<string.h> void main() { char s1[25],s2[25]; Output int c; Enter String1:abc clrscr(); Enter String2:ABC printf(“Enter string1:”); String1 > String2 gets(s1); printf(“Enter string2:”); gets(s2); c=strcmp(s1,s2); if(c>0) printf(“String1 > String2”); else if(c<0) printf(“String2 > String1”); else printf(“Both are equal”); getch(); ABHISHEK DWIVEDI 3 July 2010 }
    75. 75. strcpy() function The general form is: strcpy(String1, String2); The strcpy() function is used to copy the character string from String2 to String1. This function returns the result string String1 the String2 remains unchanged. String2 may be a character array or a string constant. ABHISHEK DWIVEDI 3 July 2010
    76. 76. strcpy() function : Program Program #include<stdio.h> #include<conio.h> #include<string.h> Output void main() Enter String1:Millennium { The String2 is:Millennium char s1[15],s2[15]; clrscr(); printf(“Enter String1:”) gets(s1); printf(“The String2 is:%s”,strcpy(s2,s1)); getch(); } ABHISHEK DWIVEDI 3 July 2010
    77. 77. strlen() function This function strlen() counts the number of characters present in a string. The counting ends at the first null character. The general form is strlen (String1); The strlen() function returns the length of the argument String1 excluding the null character. The argument may be a string constant. ABHISHEK DWIVEDI 3 July 2010
    78. 78. strlen() function : Program Program #include<stdio.h> #include<conio.h> #include<string.h> void main() Output { Enter a string: char str[30]; Millennium Software clrscr(); Solutions printf(“Enter a string:”); The length of a string gets(str); is:29 printf(“The length of a string is:%d”,strlen(str)); getch(); } ABHISHEK DWIVEDI 3 July 2010
    79. 79. strupr(), strlwr(), strrev() functions The strupr() function is used to convert the string into upper case. The strlwr() function is used to convert the string into lower case. The strrev() function prints the entire string in reverse order. ABHISHEK DWIVEDI 3 July 2010
    80. 80. strupr(), strlwr(), strrev() functions : Program Program #include<stdio.h> #include<conio.h> #include<string.h> Output void main() Enter a string:millennium { The upper case string char str[15]; is:MILLENNIUM clrscr(); The lower case string printf(“Enter a string:”); is:millennium gets(str); The reverse string is:muinnellim printf(“The upper case string is:%s”,strupr(str)); printf(“nThe lower case string is:%s”,strlwr(str)); printf(“nThe reverse string is:%s”,strrev(str)); getch(); } ABHISHEK DWIVEDI 3 July 2010
    81. 81. Functions Functions are building blocks of C. Function performs the same set of instructions on different sets of data or at different portions of a program. C functions can be classified into two categories, namely library functions and user-defined functions. main is an example of user-defined functions. printf and scanf belong to the category of library functions. The main distinction between these two categories is that library functions are not required to be written by us whereas a user-defined function has to be developed by the user at the time of writing a program. The general form of C function is Return-type Function-name (parameter list) parameter declaration; { Body of function; } ABHISHEK DWIVEDI 3 July 2010
    82. 82. Advantages of user-defined functions: It facilitates top-down modular programming. In this programming style, the high level logic of the overall problem is solved first while the details of each lower-level function are addressed later. The length of a source program can be reduced by using functions at appropriate places. This factor is particularly critical with microcomputers where memory space is limited. Many other programs may use a function. This means that a C programmer can build on what others have already done, instead of starting over, from scratch. As mentioned earlier, it is easy to locate and isolate a faulty function for further investigations. ABHISHEK DWIVEDI 3 July 2010
    83. 83. Category of functions A function, depending on whether arguments are present or not and whether a value is returned or not, may belong to one of the following categories: Category 1: Functions with no arguments and no return values. Category 2: Functions with arguments and no return values. Category 3: Functions with arguments and return values. ABHISHEK DWIVEDI 3 July 2010
    84. 84. Functions with no arguments and no return values Program #include<stdio.h> #include<conio.h> Function Declaration void printline(); void main() { clrscr(); printline(); /*Function Declaration*/ printf(“This illustrates the use of C functionsn”); printline(); getch(); } void printline() /*Return Type & Function Name*/ { int i; for(i=1;i<=40;i++) printf(“-”); printf(“n”); } ABHISHEK DWIVEDI 3 July 2010
    85. 85. Arguments but no Return values Program #include<stdio.h> #include<conio.h> void swap(int,int); void main() { int a,b; clrscr(); printf(“Enter 2 numbers:”); scanf(“%d%d”,&a,&b); swap(a,b); /* Function Call*/ getch(); } void swap(int x, int y) /*Called Function*/ { int z; z = x; x = y; y = z; printf(“nAfter swapping:%d,%d”,x,y); } ABHISHEK DWIVEDI 3 July 2010
    86. 86. Arguments with Return Values Program #include<stdio.h> #include<conio.h> int big(int,int); void main() { int a,b,max; clrscr(); printf(“Enter 2 numbers:”); scanf(“%d%d”,&a,&b); max = big(a,b); printf(“nThe biggest number is:%d”,max); getch(); } int big(int x, int y) { if(x>y) return x; else return y; } ABHISHEK DWIVEDI 3 July 2010
    87. 87. Recursion Recursion is a technique to be used to call itself. long int fact(int n) In C, it is possible for the functions to call { themselves. long int f; A function is called recursive if a statement with in if(n==1) the body of a function calls the same function itself. return 1; Program else #include<stdio.h> f = n*fact(n-1); return f; #include<conio.h> } long int fact(int); void main() { int n; long int res; clrscr(); printf(“Enter a positive number:”); scanf(“%d”,&n); res = fact(n); printf(“The factorial is:%ld”,res); getch(); } ABHISHEK DWIVEDI 3 July 2010
    88. 88. Important points about functions All C programs must contain atleast one function. [The main() function serves this rule] A function can return only one value. Thus we should not specify two values to return. The return type in function declaration is optional. If no return type is specified it is assumed to be an integer which is default. When a function is not returning any value, void type can be used as return type. Parameter list is optional. ‘C’ provides a statement return return expression Return statement is used in function definition to communicate the return value to the calling function. ABHISHEK DWIVEDI 3 July 2010
    89. 89. Important points (Contd…) Return statement indicates exit from the function and return to the point from where the function was invoked. There may be any number of return statements in function definition, but only one return statement will activate in a function call. The variable declarations within the function (between braces { }) are local to the function and are not available outside the function. If there is no return statement, the program will return to the calling point after it reaches the end of the function body (}). A function call can be used wherever a variable of same type is used (except the left side of an assignment statement). There should be one to one correspondence between the actual and formal parameters in type, order and number. C allows recursion. That is a function can call itself. A C function cannot be defined in another function. ABHISHEK DWIVEDI 3 July 2010
    90. 90. Functions with Arrays Like the values of simple variables, it is also possible to pass the values of an array to a function. To pass an array to a called function, it is sufficient to list the name of the array, without any subscripts, and the size of the array as arguments. For example, the call largest(a,n); will pass all the elements contained in the array a of size n. The called function expecting this call must be appropriately defined. The largest function header might look like: int largest(array,size); int array[]; int size; ABHISHEK DWIVEDI 3 July 2010
    91. 91. Variables There are three basic places in a C program where variables will be declared:  inside the function, in the definition of function parameters, or outside of all functions. These variables are called local variables, formal parameters, and global variables respectively. ABHISHEK DWIVEDI 3 July 2010
    92. 92. Local Variables The body of any function comprises of two parts: declaration of variables and a set of executable statements. Variables declared inside a function are called local variables. This name derives from the fact that a variable inside a function can be used only inside that function. An attempt on our part or access the local variable of one function in another, will draw an error from the compiler: Identifier undefined. ABHISHEK DWIVEDI 3 July 2010
    93. 93. Global Variables Block Variables C program consists of three sections Yet another place to declare namely: the preprocessor directives, variables is inside any block: the global variable section and finally these variables are called block the functions. variables and these can be used The variables that are declared in the only inside that block. global variable section are called global variables. While a local variable can be used only inside a function in which it is declared, a global variable can be used anywhere in the program. ABHISHEK DWIVEDI 3 July 2010
    94. 94. Storage classes The storage class of a variable dictates how, when and where storage will be allocated for the variable. The different storage classes available are: 1. Auto 2. Register 3. Extern 4. Static ABHISHEK DWIVEDI 3 July 2010
    95. 95. Auto Automatic variables are declared inside a function in which they are to be utilized. They are created when the function is called and destroyed automatically when the function is exited, hence the name automatic. Automatic variables are therefore private (or local) to the function in which they are declared. Because of this property, automatic variables are also refereed to as local or internal variables. A variable declared inside a function without storage class specification is, by default, an automatic variable. One important feature of automatic variables is that their value cannot be changed accidentally by what happens in some other function in the program. This assures that we may declare and use the same variable name in different functions in the same program without causing any confusion to the compiler. ABHISHEK DWIVEDI 3 July 2010
    96. 96. Auto : Program #include<stdio.h> void function1() #include<conio.h> { int m = 10; void function1(); printf(“%dn”,m); void function2(); } void main() void function2() { { int m = 100; int m = 1000; function1(); clrscr(); printf(“%dn”,m); } function2(); printf(“%dn”,m); getch(); } ABHISHEK DWIVEDI 3 July 2010
    97. 97. Register It is possible for use to attribute the register storage class to certain variables. We can tell the compiler that a variable should be kept in one of the machine’s registers, instead of keeping in the memory (where normal variables are stored). Since a register access is much faster than a memory access, keeping the frequently accessed variables in the register will lead to faster execution of programs. This is done as follows: register int count; The important point while using register variables is, registers of CPU do not have addresses. Thus, we should not refer the address of a register variable. For example, The following statement will result an error : register int i; scanf(“%d”,&i); ABHISHEK DWIVEDI 3 July 2010
    98. 98. Register : Program #include<stdio.h> #include<conio.h> void main() { register int count; int sum; clrscr(); for(count=0;count<10;count++) sum = sum + count; printf(“The sum is:%d”,sum); getch(); } ABHISHEK DWIVEDI 3 July 2010
    99. 99. Extern This is the default storage class for all global variables. Extern storage class variables get initialized (to zero in the case of integers) automatically, retain their value throughout the execution of the program and can be shared by different modules of the same program. However, assuming “int intvar;”is present in a.c., to be also to have proper binding with the same variable, b.c (another file) should have “extern int intvar”. ABHISHEK DWIVEDI 3 July 2010
    100. 100. Extern : Program a.c file b.c file #include<stdio.h> float f = 84.237; extern int intvar; #include<conio.h> funct(char c, int intvar) int intvar; { extern float f; char c1,c2; : void main() : { } char ch; funct(ch,intvar); printf(“%f”,f); getch(); } ABHISHEK DWIVEDI 3 July 2010
    101. 101. Static The static storage class has a number of implications depending upon its usage. The default storage class for all local variables is auto. This can be changed to static by prefixing the declaration with the keyword static as in static int intvar. A local variable with static storage class is still a local variable as far as its scope is concerned, it is still available only inside the function in which it is declared. But certain other properties of the variable change; It gets initialized to zero automatically, is initialized only once, (during program startup) and it retains its value throughout the execution of the program. When applied to a global variable, the global variable becomes inaccessible outside the file in which it is declared. This storage class can be applied to functions too. Similar to case 2, the functions become inaccessible outside the file. ABHISHEK DWIVEDI 3 July 2010
    102. 102. Static : Program Program: #include<stdio.h> #include<conio.h> void main() Output { The value of n is 1 function1( ); The value of n is 2 function1( ); The value of n is 3 function1( ); getch(); } void function1() { static int n; n++; printf(“nThe value of n is:%d”,n); } ABHISHEK DWIVEDI 3 July 2010
    103. 103. Storage Type Default Where Scope Life Storage class initial declared value Auto Local garbage within the function within the function until function is no Memory or value where it is declared longer active none Register Local garbage within the function within the function until function is no CPU value where it is declared longer active registers Static Local Zero within the function within the function until program ends, Memory where it is declared value of the variable persists between different function calls Extern Global Zero A heat of all All files including other While any of these Memory functions within a files where declared files are active. file extern That is, as long as the program’s execution doesn’t come to an end ABHISHEK DWIVEDI 3 July 2010
    104. 104. Structures A structure is a convenient tool for Example: handling a group of logically related struct book data items. These fields are called structure elements or members. { char name[20]; Declaring A Structure char author[15]; The general form of a structure int pages; declaration statement is given below: float price; struct <structure name> } { structure element1; structure element2; structure element3; ………. ………. } ABHISHEK DWIVEDI 3 July 2010
    105. 105. Important points while declaring a structure type: The closing brace in the structure type declaration must be followed by a semicolon. It is important to understand that a structure type declaration does not tell the compiler to reserve any space in memory. All a structure declaration does is, it defines the ‘form’ of the structure. Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined. ABHISHEK DWIVEDI 3 July 2010
    106. 106. ACCESSING STRUCTURES ELEMENTS We can assign values to the members of a structure in a number of ways. As mentioned earlier, the members themselves are not variables. They should be linked to the structure variables in order to make them meaningful members. The link between a member and a variable is established using the member operator ‘.’ Which is also known as ‘dot operator’ or ‘period operator’. The general form is Structure-Variable. Structure-Member; For example, book1.price; We can also use scanf to give the values through the keyboard. scanf(“%s”,book1.name); scanf(“%d”,&book1.pages); are valid input statements. ABHISHEK DWIVEDI 3 July 2010
    107. 107. ARRAYS OF STRUCTURES we may declare an array of structures, each element of the array representing a structure variable. For example, struct class student[100]; defines an array called student, that consists of 100 elements. Each element is defined to be of the type struct class. Consider the following declaration: struct marks { int sub1; int sub2; int sub3; }s[5]; ABHISHEK DWIVEDI 3 July 2010
    108. 108. ARRAYS WITHIN STRUCTURES C permits the use of arrays as structure members. We have already used arrays of characters inside a structure. Similarly, we can use single-or multi- dimensional arrays of type int or float. For example, the following structure declaration is valid: struct marks { int number; float sub[3]; }s[2]; ABHISHEK DWIVEDI 3 July 2010
    109. 109. STRUCTURES WITHIN STRUCTURES Structures within a structure means The salary structure contains a nesting of structures. Nesting of structures is permitted in C. Let us member named allowance which itself consider the following structure is a structure with three members. definition: struct salary The members contained in the inner { structure namely dearness, char name[20]; house_rent, and city can be referred to char dept[10]; as struct employee.allowance.dearness { employee.allowance.house_rent int dearness; employee.allowance.city int house_rent; int city; }allowance; }employee; ABHISHEK DWIVEDI 3 July 2010
    110. 110. UNIONS Unions are a concept borrowed from structures and therefore follow the same syntax as structures. However, there is major distinction between them in terms of storage. In structures, each member has its own storage location, whereas all the members of a union use the same location. This implies that, although a union may contain many members of different types, it can handle only one member at a time. Like structures, a union can be declared using the keyword union as follows: union item { int m; float x; char c; }code; ABHISHEK DWIVEDI 3 July 2010
    111. 111. SIZE OF STRUCTURES We normally use structures, unions, and arrays to create variables of large sizes. The actual size of these variables in terms of bytes may change from machine to machine. We may use the unary operator sizeof to tell us the size of a structure (or any variable). The expression sizeof(struct x) will evaluate the number of bytes required to hold all the members of the structure x. If y is a simple structure variable of type struct x, then the expression sizeof(y) would also give the same answer. ABHISHEK DWIVEDI 3 July 2010
    112. 112. Pointers Pointers are another important feature of C language. They are a powerful tool and handy to use once they are mastered. There are a number of reasons for using pointers. A pointer enables us to access a variable that is defined outside the function. Pointers are more efficient in handling the data tables. Pointers reduce the length and complexity of a program. They increase the execution speed. The use of a pointer array to character strings results in saving of data storage space in memory. ABHISHEK DWIVEDI 3 July 2010
    113. 113. ACCESSING THE ADDRESS OF A VARIABLE The actual location of a variable in the memory is system dependent and therefore, the address of a variable is not known to us immediately. We can determine the address of the variable with the help of the operator & in C. We have already seen the use of this address operator in the scanf function. The operator & immediately preceding a variable returns the address of the variable associated with it. For example, p = &quantity; would assign the address to the variable p. The & operator can be remembered as ‘address of’. ABHISHEK DWIVEDI 3 July 2010
    114. 114. ACCESSING ADDRESSES OF VARIABLES : PROGRAM #include<stdio.h> #include<conio.h> void main() { char a; int x; float p, q; clrscr(); a = ‘A’; x = 125; p = 10.25, q = 18.76; printf(“%c is stored at address %u”, a, &a); printf(“n%d is stored at address %u”, x, &x); printf(“n%f is stored at address %u”, p, &p); printf(“n%f is stored at address %u”, q, &q); getch(); } ABHISHEK DWIVEDI 3 July 2010
    115. 115. DECLARING POINTERS In C, every variable must be declared for its For example, type. Since pointer variables contain int *p; addresses that belong to a separate data declares the variable p as a pointer type, they must be declared as pointers variable that points to an integer data before we use them. type. The declaration of a pointer variable takes Remember that the type int refers to the following form: the data type of the variable being datatype *pt_name; pointed to by p and not the type of the value of the pointer. This tells the compiler three things about the variable pt_name. Similarly, the statement float *x; The asterisk (*) tells the variable declares x as a pointer to a floating pt_name is a pointer variable. point variable. pt_name needs a memory location. pt_name points to a variable of type datatype. ABHISHEK DWIVEDI 3 July 2010
    116. 116. INITIALIZING POINTERS Once a pointer variable has been A pointer variable can be declared, it can be made to point to a initialized in its declaration itself. variable using an assignment For example, statement such as int x, *p=&x; p = &quantity; is perfectly valid. It declares x as an integer variable and p as a which causes p to point to quantity. pointer variable and then That is, p now contains the address of initializes p to the address of x. quantity. Note carefully that this is an This is known as pointer initialization. initialization of p, not *p. And Before a pointer is initialized, it should also remember that the target not be used. variable x is declared first. The statement int *p=&x, x; is not valid. ABHISHEK DWIVEDI 3 July 2010
    117. 117. ACCESSING A VARIABLE THROUGH ITS POINTER Once a pointer has been assigned the address of a variable, the question remains as to how to access the value of the variable using the pointer. This is done by using another unary operator * (asterisk), usually known as the indirection operator. Consider the following statements: int quantity, *p, n; quantity = 179; p = &quantity; n = *p; ABHISHEK DWIVEDI 3 July 2010
    118. 118. ACCESSING A VARIABLE THROUGH ITS POINTER (CONTD…) The first line declares quantity and n as integer variables and p as a pointer variable pointing to an integer. The second line assigns the value 179 to quantity. The third line assigns the address of quantity to the pointer variable p. The fourth line contains the indirection operator *. When the operator * is placed before a pointer variable in an expression, the pointer returns the value of the variable of which the pointer value is the address. In this case, *p returns the value of the variable quantity, because p is the address of quantity. The * can be remembered as ‘value of address’. Thus the value of n would be 179. ABHISHEK DWIVEDI 3 July 2010
    119. 119. POINTERS AND ARRAYS When an array is declared, the If we declare p as an integer pointer, compiler allocates a base address and then we can make the pointer p to sufficient amount of storage to contain point to the array x by the following all the elements of the array in assignment: contiguous memory locations. p = x; The base address is the location of the This is equivalent to first element (index 0) of the array. The p = &x[0]; compiler also defines the array name When handling arrays, instead of as a constant pointer to the first using array indexing, we can use element. pointers to access array elements. Note that *(p+3) gives the value of x[3]. The pointer accessing method is much faster than array indexing. ABHISHEK DWIVEDI 3 July 2010
    120. 120. DYNAMIC MEMORY ALLOCATION C language requires the number of elements in an array to be specified at compile time. But we may not be able to do so always. Our initial judgment of size, if it is wrong, may cause failure of the program or wastage of memory space. Many languages permit a programmer to specify an array’s size at run time. The process of allocating memory at run time is known as dynamic memory allocation. In C language there are four library routines known as “memory management functions” that can be used for allocating and freeing memory during program execution. ABHISHEK DWIVEDI 3 July 2010
    121. 121. Memory Allocation Functions Function Task malloc Allocates requested size of bytes and returns a pointer to the first byte of the allocated space. calloc Allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory. Free Frees previously allocated space. realloc Modifies the size of previously allocated space. ABHISHEK DWIVEDI 3 July 2010
    122. 122. Allocating a Block of Memory A block of memory may be allocated Use of malloc Function using the function malloc. The malloc #include<stdio.h> function reserves a block of memory #include<conio.h> of specified size and returns a pointer void main() of type void. This means that we can { assign it to any type of pointer. int *p, n, i; It takes the following form: clrscr(); printf(“Enter n value:”); ptr = (datatype *)malloc(byte-size); scanf(“%d”,&n); ptr is a pointer of type datatype. The p = (int) malloc(sizeof(int)*n); malloc returns a pointer (of datatype) printf(“nEnter %d numbers:”,n); to an area of memory with size byte- for(i=0;i<n;i++) size. scanf(“%d”,*(p+i)); Example: printf(“nThe numbers are:”); for(i=0;i<n;i++) x = (int *) malloc (sizeof(int) * n); printf(“n%d”,*(p+i)); getch(); } ABHISHEK DWIVEDI 3 July 2010
    123. 123. Allocating Multiple Blocks of Memory calloc is another memory allocation function that is normally used for requesting memory space at run time for storing derived data types such as arrays and structures. While malloc allocates a single block of storage space, calloc allocates multiple blocks of storage, each of the same size, and then sets all bytes to zero. The general form of calloc is: ptr = (datatype *) calloc (n,elem-size); The above statement allocates contiguous space for n blocks, each of size elem-size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space, a NULL pointer is returned. ABHISHEK DWIVEDI 3 July 2010
    124. 124. Releasing the Used Space Compile-time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic run-time allocation, it is our responsibility to release the space when it is not required. The release of storage space becomes important when the storage is limited. We may release that block of memory for future use, using the free function: free(ptr); ptr is a pointer to a memory block which has already been created by malloc or calloc. ABHISHEK DWIVEDI 3 July 2010
    125. 125. Altering the Size of a Block It is likely that we discover later, the previously allocated memory is not sufficient and we need additional space for more elements. It is also possible that the memory allocated is much larger than necessary and we want to reduce it. In both the cases, we can change the memory size already allocated with the help of the function realloc. This process is called the reallocation of memory. For example, if the original allocation is done by the statement ptr = malloc(size); then reallocation of space may be done by the statement ptr = realloc(ptr, newsize); ABHISHEK DWIVEDI 3 July 2010
    126. 126. POINTERS AND CHARACTER STRINGS Program We know that a string is an array of #include<stdio.h> characters, terminated with a null #include<conio.h> character. void main() { Like in one-dimensional arrays, we can char *str; use a pointer to access the individual int i=0; characters in a string. clrscr(); printf(“Enter a string:”); gets(str); while(*str!=’0’) { i++; str++; } printf(“nThe length is:%d”,i); getch(); } ABHISHEK DWIVEDI 3 July 2010
    127. 127. POINTERS AND FUNCTIONS Program : Pointers as function Parameters #include<stdio.h> In functions we can pass the duplicate #include<conio.h> values for the actual parameters, but void main() we can pass the address of a variable as { an argument to a function in the int a,b; normal fashion. clrscr(); printf(“Enter 2 numbers:”); When we pass addresses to a function, scanf(“%d %d”,&a,&b); the parameters receiving the addresses printf(“nBefore exchange: a=%d, b=%d”,a, b); should be pointers. The process of swap(&a,&b); calling a function using pointers to pass printf(“nAfter exchange: a=%d, b=%d”,a, b); the addresses of variable is known as getch(); } call by address. void swap(int *x, int *y) { int z; z = *x; *x = *y; *y = z; } ABHISHEK DWIVEDI 3 July 2010
    128. 128. POINTERS AND STRUCTURES We know that the name of an array stands for Program: Pointers to Structure variables the address of its zeroth element. The same #include<stdio.h> thing is true of the names of arrays of structure #include<conio.h> variables. struct invent { Suppose product is an array variable of struct char name[20] ; type. The name product represents the int number; address of its zeroth element. }product[3], *ptr; Consider the following declaration: void main() { struct inventory clrscr(); { printf(“INPUTnn”); printf(“Enter name and number(3 records):”); char name[30]; for(ptr = product;ptr<product+3;ptr++) int number; scanf(“%s %d”,ptr->name,&ptr->number); printf(“nnOUTPUT”); } product[3], *ptr; for(ptr = product;ptr<product+3;ptr++) printf(“n%st%d”,ptr->name,ptr->number); getch(); } ABHISHEK DWIVEDI 3 July 2010
    129. 129. File Management in C A file is a place on the disk where a group of related data is stored. Like most other languages, C supports a number of functions that have the ability to perform basic file operations, which include:  Naming a file,  Opening a file,  Reading data from a file,  Writing data to a file, and  Closing a file. ABHISHEK DWIVEDI 3 July 2010
    130. 130. High level I/O functions Function Name Operation fopen() Creates a new file for use Opens an existing file for use. fclose() Closes a file which has been opened for use. Getc() Reads a character from a file. putc() Writes a character to a file. fprintf() Writes a set of data values to a file. fscanf() Reads a set of data values from a file. getw() Reads an integer from a file. putw() Writes an integer to file. fseek() Sets the position to a desired point in the file Ftell() Gives the current position in the file rewind() Sets the position to the beginning of the file. ABHISHEK DWIVEDI 3 July 2010
    131. 131. DEFINING AND OPENING A FILE If we want to store data in a file in the secondary memory, we must specify certain things about the file, to the operating system. They include: Filename. Data Structure. Purpose. Following is the general format for declaring and opening a file: FILE *fp; fp = fopen(“filename”, “mode”); ABHISHEK DWIVEDI 3 July 2010
    132. 132. DEFINING AND OPENING A FILE (CONTD…) The first statement declares the variable fp as a “pointer to the data type FILE”. As stated earlier, FILE is a structure that is defined in the I/O library. The second statement opens the file named filename and assigns as identifier to the FILE the pointer fp. This pointer which contains all the information about the file is subsequently used as a communication link between the system and the program. The second statement also specifies the purpose of opening this file. The mode does this job. Mode can be one of the following: r open the file for reading only. w open the file for writing only. a open the file for appending (or adding) data to it. Note that both the filename and mode are specified as strings. They should be enclosed in double quotation marks. ABHISHEK DWIVEDI 3 July 2010
    133. 133. DEFINING AND OPENING A FILE (CONTD…) When trying to open a file, one of the Consider the following statements: following things may happen: FILE *p1, *p2; When the mode is ‘writing’ a file with p1 = fopen(“data”,”r”); the specified name is created if the file p2 = fopen(“results”,”w”); does not exist. The contents are deleted, if the file already exists. Many recent compilers include additional modes of operation. They When the purpose is ‘appending’, the include: file is opened with the current contents r+ The existing file is opened to the safe. A file with the specified name is beginning for both reading and writing. created if the file does not exist. w+ Same as w except both for reading If the purpose is ‘reading’, and if it and writing exists, then the file is opened with the a+ Same as a except both for reading current contents safe; otherwise an and writing. error occurs. We can open and use a number of files at a time. This number however depends on the system we use. ABHISHEK DWIVEDI 3 July 2010
    134. 134. CLOSING A FILE A file must be closed as soon as all operations on it have been completed. The general form is: fclose(file_pointer); ABHISHEK DWIVEDI 3 July 2010
    135. 135. INPUT/OUTPUT OPERATIONS ON FILES Once a file is opened, reading out of or writing to it is accomplished using the standard I/O routines that are listed. The getc and putc Functions The simplest file I/O functions are getc and putc. These are analogous to getchar and putchar functions and handle one character at a time. Assume that a file is opened with mode w and file pointer fp1. Then, the statement putc(c, fp1); writes the character contained in the character variable c to the file associated with FILE pointer fp1. Similarly, getc is used to read a character from a file that has been opened in read mode. For example, the statement c = getc(fp2); would read a character from the file whose file pointer is fp2. The file pointer moves by one character position for every operation of getc or putc. The getc will return an end-of-file marker EOF, when end of the file has been reached. Therefore, the reading should be terminated when EOF is encountered. ABHISHEK DWIVEDI 3 July 2010
    136. 136. Program : Writing to and Reading from a File PROGRAM #include<stdio.h> #include<conio.h> void main() { FILE *f1; char c; clrscr(); printf(“Data Inputnn”); f1 = fopen(“INPUT”, “w”); while((c=getchar()!=EOF) putc(c,f1); fclose(f1); printf(“nData Outputnn”); f1 = fopen(“INPUT”,”r”); while((c=getc(f1))!=EOF) printf(“%c”,c); fclose(f1); getch(); } ABHISHEK DWIVEDI 3 July 2010
    137. 137. The fprintf & fscanf Functions The functions fprintf and fscanf perform I/O operations that are identical to the familiar printf and scanf functions, except of course that they work on files. The first argument of these functions is a file pointer which specifies the file to be used. The general form of fprintf is fprintf(fp, “control string”, list); where fp is a file pointer associated with a file that has been opened for writing. The control string contains output specifications for the items in the list. The list may include variables, constants and strings. Example: fprintf(f1, “%s %d %f”,name,age,7.5); Here, name is an array variable of type char and age is int variable. ABHISHEK DWIVEDI 3 July 2010
    138. 138. The fscanf Function The general format of fscanf is fscanf(fp, “control string”, list); This statement would cause the reading of the items in the list from the file specified by fp, according to the specifications contained in the control string. Example: fscanf(f2, “%s %d”, item, &quantity); Like scanf, fscanf also returns the number of items that are successfully read. When the end of file is reached, it returns the value of EOF. ABHISHEK DWIVEDI 3 July 2010
    139. 139. COMMAND LINE ARGUMENTS It is a parameter supplied to a program when the program is invoked. This parameter may represent a filename the program should process. For example, if we want to execute a program to copy the contents of a file named X_FILE to another one named Y_FILE, then we may use a command line like C:TC>PROGRAM X_FILE Y_FILE PROGRAM is the filename where the executable code of the program is stored. This eliminates the need for the program to request the user to enter the filenames during execution. ABHISHEK DWIVEDI 3 July 2010

    ×