Presentation is loading. Please wait.

Presentation is loading. Please wait.

Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine.

Similar presentations


Presentation on theme: "Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine."— Presentation transcript:

1

2 Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine : A machine is any device that uses energy to perform some activity. Data : In computer science, data is anything in a form suitable for use with a computer. Instructions: In computer science, source code is any sequence of statements or declarations written in some human-readable computer programming language. A computer is a machine that manipulates data according to a list of instructions. Machine : A machine is any device that uses energy to perform some activity. Data : In computer science, data is anything in a form suitable for use with a computer. Instructions: In computer science, source code is any sequence of statements or declarations written in some human-readable computer programming language. October 10, 20141

3 Session # 2 [Introduction to Computers] Data Vs. Information  Data Collection of raw facts are nothing but data. In fact it is plural, singular for this is datum. ex:  Information Processed data is the nothing but Information. ex:  Data Collection of raw facts are nothing but data. In fact it is plural, singular for this is datum. ex:  Information Processed data is the nothing but Information. ex: October 10, Roll NoSub CodeS1S2S3A1A2A3 Y7CSE11CSE Y7CSE12CSE Y7CSE13CSE Roll NoSub CodeMarks Y7CSE11CSE31129 Y7CSE12CSE31129 Y7CSE13CSE31126

4 Session # 2 [Introduction to Computers] Data Processing Activities October 10, Capturing Input Data Data to be processed is to be captured first. The Common way to complete this activity is Paper form Manipulating Captured Data Classifying – Arranging the similar items into Groups or Classes Calculating –Doing Arithmetic Operations like addition, subtraction, multiplication etc.. Sorting - Arranging the items in a logical sequence Summary - For reducing masses of information Managing Output Results Storing and Retrieval operation Reproducing and Communicating

5 Session # 2 [Introduction to Computers] Computer Processing Capabilities October 10, Input output operations Text manipulation and calculation operations Logical and Comparison operations Storing and Retrieval operations

6 Session # 2 [Introduction to Computers] Computer Processing Capabilities October 10, Input UnitOutput Unit Primary Memory [RAM] ALUCU Secondary Memory [ H. D] Input unit output unit Primary memory [ram] ALU CU Secondary memory[H.D ]

7 Session # 2 [Introduction to Computers] Computer Programming Languages October 10, 20146

8 Session # 2 [Introduction to Computers] Computer Language Translators Compiler : A compiler is a computer program (or set of programs) that translates text written in a computer language (the source language) into another computer language (the target language). The original sequence is usually called the source code and the output called object code. The name "compiler" is primarily used for programs that translate source code from a high- level programming language to a lower level language (e.g., assembly language or machine language) Interpreter : An interpreter may be a program that either  executes the source code directly  translates source code into some efficient intermediate representation (code) and immediately executes this  explicitly executes stored precompiled code made by a compiler which is part of the interpreter system Compiler : A compiler is a computer program (or set of programs) that translates text written in a computer language (the source language) into another computer language (the target language). The original sequence is usually called the source code and the output called object code. The name "compiler" is primarily used for programs that translate source code from a high- level programming language to a lower level language (e.g., assembly language or machine language) Interpreter : An interpreter may be a program that either  executes the source code directly  translates source code into some efficient intermediate representation (code) and immediately executes this  explicitly executes stored precompiled code made by a compiler which is part of the interpreter system October 10, 20147

9 Session # 3 [C Fundamentals] An Overview of C History of C language : Characteristics of C’ language:  Middle level Language [ It has good qualities of both high/low level languages]  Structured Programming Language  Programmer’s Language History of C language : Characteristics of C’ language:  Middle level Language [ It has good qualities of both high/low level languages]  Structured Programming Language  Programmer’s Language October 10, 20148

10 Session # 3 [C Fundamentals] C Character Set C Character set Includes October 10, 20149

11 Session # 3 [C Fundamentals] Identifiers Identifiers Identifiers are used to identify some programming elements like, variables, arrays, pointers, functions, and user defined things. The following are the rules to construct valid identifiers. We have to use only alphabets, digits and one special character [ _ ] underscore. The first letter must not be a digit The length of these identifiers may vary from one to several characters. Identifier name should not be same as a C keyword. Identifiers Identifiers are used to identify some programming elements like, variables, arrays, pointers, functions, and user defined things. The following are the rules to construct valid identifiers. We have to use only alphabets, digits and one special character [ _ ] underscore. The first letter must not be a digit The length of these identifiers may vary from one to several characters. Identifier name should not be same as a C keyword. October 10,

12 Session # 3 [C Fundamentals] keywords Keywords a few words are reserved for particular programming purpose in all most all modern programming languages. C’ also have reserved a few words to play key role in programming purpose. They are as follows. Keywords a few words are reserved for particular programming purpose in all most all modern programming languages. C’ also have reserved a few words to play key role in programming purpose. They are as follows. October 10, auto breakcasechar constcontinuedefault do doubleelseenumextern float forgotoif intlongregisterreturn shortsignedsizeofstatic structswitchtypedefunionunsignedvoidvolatilewhile

13 Session # 3 [C Fundamentals] Literals October 10,

14 Session # 3 [C Fundamentals] Variables Variables: While solving a problem we may need to remember some data values temporarily. Such values are placed in the named locations in the memory. These named locations in the memory are called variables. To create a location in the memory, system needs three specifications Variables: While solving a problem we may need to remember some data values temporarily. Such values are placed in the named locations in the memory. These named locations in the memory are called variables. To create a location in the memory, system needs three specifications October 10, Name of the location. Type of value the location has to hold. Set of operations that are going to be performed against the location.

15 Session # 3 [C Fundamentals] Variables Declarations You create location or locations in the memory with these specifications, we can specify to the system through variable declaration statement. Its syntax is: type variablelist; To declare single variable: type variablename; Note: Variable name should be valid identifier. Remaining two specifications we are specifying through data type. You create location or locations in the memory with these specifications, we can specify to the system through variable declaration statement. Its syntax is: type variablelist; To declare single variable: type variablename; Note: Variable name should be valid identifier. Remaining two specifications we are specifying through data type. October 10,

16 Session # 3 [C Fundamentals] Data Types Data Types It defines two things  Type of value, the location has to hold,  Set of operations may be performed against the location. C supports 5 foundational data types Data Types It defines two things  Type of value, the location has to hold,  Set of operations may be performed against the location. C supports 5 foundational data types October 10,

17 Session # 3 [C Fundamentals] Variable Declaration Examples October 10, char char ch;[single] char ch1,ch2,ch3[list] int int x;int no1,no2,no3,sum; float float f;float x,y,avg; double double d;double p,q,r;

18 Session # 4 [Operators] Introduction to Operators Operators: Operators are symbols that perform a particular operation on operands. Here operands might be variables/constants. note: operators and operands are collectively form C’ expressions. ex: ‘+’ operator performs an addition operation Depending on the number of operands the operator is expecting, all operators are classified into 3 types: Operators: Operators are symbols that perform a particular operation on operands. Here operands might be variables/constants. note: operators and operands are collectively form C’ expressions. ex: ‘+’ operator performs an addition operation Depending on the number of operands the operator is expecting, all operators are classified into 3 types: October 10, Unary [works on single operand]Binary [works on two operands]Ternary [works on three operands]

19 Session # 4 [Operators] Assignment Operator Assignment Operator [ = ] In ‘c’, (=) is the assignment operator, it performs the assignment operation. Assignment statement is constructed by using this operator. Syntax :variable= value/expression; ex: int a = 67; Multiple Assignments to store 5 integers constants temporary we need 5 variables of int type. int a, b, c, d, e; to assign 10 in all these locations a = 10; b = 10; c = 10; d = 10; e = 10; Instead of 5 assignment statements we can manage with single assignment statement as a = b = c = d = e = 10; Assignment Operator [ = ] In ‘c’, (=) is the assignment operator, it performs the assignment operation. Assignment statement is constructed by using this operator. Syntax :variable= value/expression; ex: int a = 67; Multiple Assignments to store 5 integers constants temporary we need 5 variables of int type. int a, b, c, d, e; to assign 10 in all these locations a = 10; b = 10; c = 10; d = 10; e = 10; Instead of 5 assignment statements we can manage with single assignment statement as a = b = c = d = e = 10; October 10,

20 Session # 4 [Operators] Arithmetic Operators Arithmetic Operators October 10,

21 Session #4 [Operators] Increment and Decrement Operators Increment and Decrement Operators (++) is an increment operator. it increments its operand value by 1. ( -- ) is a decrement operator. it decrements its operand value by 1. Both operators are unary operators. They expect numeric or char type variable as operand. ex : i + + ; is equivalent to i = i + 1 ; These two operators can precede the operand or can follow the operand + + i prefix form i + + post fix form There is no difference between prefix form and postfix form in short expressions but there is difference in long expression. Increment and Decrement Operators (++) is an increment operator. it increments its operand value by 1. ( -- ) is a decrement operator. it decrements its operand value by 1. Both operators are unary operators. They expect numeric or char type variable as operand. ex : i + + ; is equivalent to i = i + 1 ; These two operators can precede the operand or can follow the operand + + i prefix form i + + post fix form There is no difference between prefix form and postfix form in short expressions but there is difference in long expression. October 10, prefixpostfix expressiona=10, b; b=++a; a=10, b; b=a++; resulta=11 b=11 a=11 b=10

22 Session # 5 [Operators] Relational Operators Relational Operators(outcome to any relational expression is either nonzero(or) zero) October 10, C relational OperatorsExample of C conditionMeaning of the condition Equality Operators ===x==yx is equals to y not =!=x!=yx is not equals to y Relational Operators >>x > yx is greater than y <= x >= yx is greater or equals to y <= x <=yx is less or equal to y

23 Session # 5 [Operators] Logical Operators Logical Operators && ( logical AND ) Returns true if both conditions are true || ( logical OR ) Returns true if either of its conditions are true ! ( logical NOT, logical negation ) Reverses the truth/falsity of its condition Unary operator, has one operand Truth Table Logical Operators && ( logical AND ) Returns true if both conditions are true || ( logical OR ) Returns true if either of its conditions are true ! ( logical NOT, logical negation ) Reverses the truth/falsity of its condition Unary operator, has one operand Truth Table October 10, exp1exp2exp1 && exp2exp1 || exp2!exp1 False True FalseTrueFalseTrue False Truefalse True false

24 Session # 5 [Operators] Conditional Operator Conditional Operator [? : ] ternary operator. Syntax expression 1 ? expression 2 : expression 3; The expression 1 is evaluated first and if the outcome of expression 1 is true then the outcome of the complete expression is expression 2 otherwise the outcome of the complete expression is expression 3. Conditional Operator [? : ] ternary operator. Syntax expression 1 ? expression 2 : expression 3; The expression 1 is evaluated first and if the outcome of expression 1 is true then the outcome of the complete expression is expression 2 otherwise the outcome of the complete expression is expression 3. October 10, exp1 exp2 exp3 true false

25 Session # 5 [Operators] Bit wise Operator Bitwise Operators All data represented internally as sequences of bits  Each bit can be either 0 or 1  Sequence of 8 bits forms a byte Bitwise Operators All data represented internally as sequences of bits  Each bit can be either 0 or 1  Sequence of 8 bits forms a byte October 10, OperatorNameDescription &bitwise AND The bits in the result are set to 1 if the corresponding bits in the two operands are both 1. |bitwise OR The bits in the result are set to 1 if at least one of the corresponding bits in the two operands is 1. ^bitwise exclusive OR The bits in the result are set to 1 if exactly one of the corresponding bits in the two operands is 1. <>right shift Shifts the bits of the first operand right by the number of bits specified by the second operand; the method of filling from the left is machine dependent. ~One’s complementAll 0 bits are set to 1 and all 1 bits are set to 0.

26 Session # 5 [Operators] Pointer Operators Pointer Operators There are two pointer operators: * and &. & (Address Of): The & is a unary operator that returns the memory address of its operand. Example: int count,*m; m=&count; The first statement will create one variable with name count and pointer with name m of int type. The second statement places address of count variable into the pointer variable m. You can think of & has returning “the address of”. Therefore the preceding statement can be verbalized as “m receives the address of count". *( At address): The second pointer operator is the compliment of &, This is also a unary operator that returns the value located at that address. Example: q=*m; Pointer Operators There are two pointer operators: * and &. & (Address Of): The & is a unary operator that returns the memory address of its operand. Example: int count,*m; m=&count; The first statement will create one variable with name count and pointer with name m of int type. The second statement places address of count variable into the pointer variable m. You can think of & has returning “the address of”. Therefore the preceding statement can be verbalized as “m receives the address of count". *( At address): The second pointer operator is the compliment of &, This is also a unary operator that returns the value located at that address. Example: q=*m; October 10,

27 Session # 5 [Operators] Operator Precedence and Associativity October 10, Operator Description Associativity () []. -> Parentheses (function call) (see Note 1) Brackets (array subscript) Member selection via object name Member selection via pointer Postfix increment/decrement (see Note 2) left-to-right ! ~ (type) * & sizeof Prefix increment/decrement Unary plus/minus Logical negation/bitwise complement Cast (change type) Dereference Address Determine size in bytes right-to-left * / %Multiplication/division/modulus left-to-right + -Addition/subtraction left-to-right

28 Session # 5 [Operators] Operator Precedence and Associativity October 10, >Bitwise shift left, Bitwise shift right left-to-right >= Relational less than/less than or equal to Relational greater than/greater or equal to left-to-right == !=Relational is equal to/is not equal to left-to-right &Bitwise AND left-to-right ^ Bitwise exclusive ORleft-to-right |Bitwise inclusive OR left-to-right &&Logical AND left-to-right ||Logical OR left-to-right ?:Ternary conditional right-to-left

29 Session # 5 [Operators] Operator Precedence and Associativity October 10, = += -= *= /= %= &= ^= |= >= Assignment Addition/subtraction assignment Multiplication/division assignment Modulus/bitwise AND assignment Bitwise exclusive/inclusive OR assignment Bitwise shift left/right assignment right-to-left, Comma (separate expressions) left-to-right Note 1: Parentheses are also used to group expressions to force a different order of evaluation; such parenthetical expressions can be nested and are evaluated from inner to outer Note 2: Postfix increment/decrement have high precedence, but the actual increment or decrement of the operand is delayed (to be accomplished sometime before the statement completes execution). So in the statement y = x * z++; the current value of z is used to evaluate the expression (i.e., z++ evaluates to z) and z only incremented after all else is done. Casts You can force an expression to be of a specific type by using a cast. The general form of a cast is (type) expression(Here type is a valid data type.) For example, to cause the expression x/2 to evaluate to type float, write (float) x/2

30 Session # 6 [Console I/O] Input Output Statements Console I/O Introduction Files and streams In C any physical device which is used to do input or output operations is called file. Examples: Keyboard, Screen, Printer, Disk file, etc... Stream A stream is a logical device, which is an abstraction between the physical device and program. Via streams only input output operations takes place. There are two types of streams.  Text Stream  Binary Stream In fact we read from the source, and write to the sink. Console I/O Introduction Files and streams In C any physical device which is used to do input or output operations is called file. Examples: Keyboard, Screen, Printer, Disk file, etc... Stream A stream is a logical device, which is an abstraction between the physical device and program. Via streams only input output operations takes place. There are two types of streams.  Text Stream  Binary Stream In fact we read from the source, and write to the sink. October 10,

31 Session # 6 [Console I/O] Reading Data from Source Reading Data from Source To read data from source do the following. Reading Data from Source To read data from source do the following. October 10, Open Text/Binary Stream in Read Mode Associate it the Source Read data from Stream, it in turn reads from the Source

32 Session # 6 [Console I/O] Writing data to the Sink Writing Data to Sink To write data to the sink,do the following. Writing Data to Sink To write data to the sink,do the following. October 10, Open Text/Binary Stream in Write/Append Mode Associate it the Sink Write data to Stream, it in turn writes to the Sink

33 Session # 6 [Console I/O] Standard Streams Standard Streams To read data from user via keyboard or to give output to the user via screen we need not do first two steps in reading and writing because when C program execution is started some predefined streams are opened automatically. They are Standard Streams To read data from user via keyboard or to give output to the user via screen we need not do first two steps in reading and writing because when C program execution is started some predefined streams are opened automatically. They are October 10,

34 Session # 7 [Console I/O] Unformatted and Formatted Functions Built in Functions To write data to stdout we have putchar (), puts (),printf() built-in functions. putchar () Syntax: #include int putchar( int ch ); The putchar() function writes ch to STDOUT. The code putchar( ch ); puts() Syntax: #include int puts( char *str ); The function puts() writes str to STDOUT. puts() returns non-negative on success, or EOF on failure Built in Functions To write data to stdout we have putchar (), puts (),printf() built-in functions. putchar () Syntax: #include int putchar( int ch ); The putchar() function writes ch to STDOUT. The code putchar( ch ); puts() Syntax: #include int puts( char *str ); The function puts() writes str to STDOUT. puts() returns non-negative on success, or EOF on failure October 10,

35 Session # 7 [Console I/O] Unformatted and Formatted Functions Built in Functions printf () Syntax: #include int printf( const char *format,... ); The printf() function prints output to STDOUT, according to format and other arguments passed to printf(). The string format consists of two types of items - characters that will be printed to the screen, and format commands that define how the other arguments to printf() are displayed. Basically, you specify a format string that has text in it, as well as "special" characters that map to the other arguments of printf(). For example, this code char name[20] = "Bob"; int age = 21; printf( "Hello %s, you are %d years old\n", name, age ); Displays the following output: Hello Bob, you are 21 years old The %s means, "insert the first argument, a string, right here." The %d indicates that the second argument (an integer) should be placed there. There are different %-codes for different variable types, as well as options to limit the length of the variables and whatnot. Built in Functions printf () Syntax: #include int printf( const char *format,... ); The printf() function prints output to STDOUT, according to format and other arguments passed to printf(). The string format consists of two types of items - characters that will be printed to the screen, and format commands that define how the other arguments to printf() are displayed. Basically, you specify a format string that has text in it, as well as "special" characters that map to the other arguments of printf(). For example, this code char name[20] = "Bob"; int age = 21; printf( "Hello %s, you are %d years old\n", name, age ); Displays the following output: Hello Bob, you are 21 years old The %s means, "insert the first argument, a string, right here." The %d indicates that the second argument (an integer) should be placed there. There are different %-codes for different variable types, as well as options to limit the length of the variables and whatnot. October 10,

36 Session # 7 [Console I/O] Format Specifiers Format Specifiers: October 10, codeformatCodeformat %cCharacter%oOctal %dsigned integers%sa string of characters %isigned integers%uunsigned integer %escientific notation, with a lowercase "e"%x unsigned hexadecimal, with lowercase letters %Escientific notation, with a uppercase "E"%X unsigned hexadecimal, with uppercase letters %ffloating point%pa pointer %guse %e or %f, whichever is shorter%n the argument shall be a pointer to an integer into which is placed the number of characters written so far %Guse %E or %f, whichever is shorter%a '%' sign

37 Session # 9 [introduction to C Program] Form of a C program THE FORM OF C’ PROGRAM # include.Preprocessor directives # include User function declarations (prototypes) if any Variables declarations if any int main (void) { Statements; } returntype function1 (parameter list) { Statements; }. returntype functionN (parameter list) { Statements; } note: red in color specifies to be optional THE FORM OF C’ PROGRAM # include.Preprocessor directives # include User function declarations (prototypes) if any Variables declarations if any int main (void) { Statements; } returntype function1 (parameter list) { Statements; }. returntype functionN (parameter list) { Statements; } note: red in color specifies to be optional October 10,

38 Session # 9 [introduction to C Program] First C program A SIMPLE C’ PROGRAM #include /* no user function declarations [prototypes] no global variables */ int main (void) { clrscr (); printf (“Welcome to SSIT”); getche(); } A SIMPLE C’ PROGRAM #include /* no user function declarations [prototypes] no global variables */ int main (void) { clrscr (); printf (“Welcome to SSIT”); getche(); } October 10,

39 Session # 9 [introduction to C Program] Program Development Process Analyze the given problem and design solution with the following strategy. October 10,

40 Session #9 [introduction to C Program] Computer Algorithm and Flow Chart What is a computer algorithm? To make a computer do anything, you have to write a computer program. To write a computer program, you have to tell the computer, step by step, exactly what you want it to do. The computer then "executes" the program, following each step mechanically, to accomplish the end goal. When you are telling the computer what to do, you also get to choose how it's going to do it. That's where computer algorithms come in. The algorithm is the basic technique used to get the job done. Let's follow an example to help get an understanding of the algorithm concept. What is a Flow chart? A flowchart illustrates the steps in a process. By visualizing the process, a flowchart can quickly help identify bottlenecks or inefficiencies where the process can be streamlined or improved. What is a computer algorithm? To make a computer do anything, you have to write a computer program. To write a computer program, you have to tell the computer, step by step, exactly what you want it to do. The computer then "executes" the program, following each step mechanically, to accomplish the end goal. When you are telling the computer what to do, you also get to choose how it's going to do it. That's where computer algorithms come in. The algorithm is the basic technique used to get the job done. Let's follow an example to help get an understanding of the algorithm concept. What is a Flow chart? A flowchart illustrates the steps in a process. By visualizing the process, a flowchart can quickly help identify bottlenecks or inefficiencies where the process can be streamlined or improved. October 10,

41 Session # 9 [introduction to C Program] Example Program Problem: Program to compute the sum of given two numbers Step 1: Problem: Program to compute the sum of given two numbers Step 1: October 10,

42 Session # 9 [introduction to C Program] Example Program Step 2: October 10,

43 Session # 9 [introduction to C Program] Example Program Flow Chart October 10, Start Clear the Screen Enter no1: Read no1 Enter no2 Read no2 Print “no1+no2=no1+no2” Stop

44 Session # 9 [introduction to C Program] Example Program Program #include /* no global variables no user function declarations (prototypes) */ int main(void) Block starts here int no1,no2; // declatation statement clrscr(); // call statement printf(“enter no1:”); // call statement scanf(“%d”,&no1); // call statement printf(“enter no2:”); // call statement scanf(“%d”,&no2); // call statement printf(“%d + %d = %d”,no1,no2,no1+no2); getche(); // call statement return 0; // jump statement Block ends here Program #include /* no global variables no user function declarations (prototypes) */ int main(void) Block starts here int no1,no2; // declatation statement clrscr(); // call statement printf(“enter no1:”); // call statement scanf(“%d”,&no1); // call statement printf(“enter no2:”); // call statement scanf(“%d”,&no2); // call statement printf(“%d + %d = %d”,no1,no2,no1+no2); getche(); // call statement return 0; // jump statement Block ends here October 10,

45 Session # 10 [Statements] Types of Statements To do this, we can specify to the system by using statement. A statement is a complete instruction categorizes statements into these groups: October 10,

46 Session # 10 [Statements] Control Statements C program control statements can be put into the following categories. October 10, Control Statements SelectionIterationJump -if, switch for, while, do goto, break, continue, return

47 Session # 10 [Statements] Selection Statements Selection Statements C supports two selection statements: if and switch. In addition, the (? :) operator is an alternative to if in certain circumstances. If The general form of the if statement is If(expression) statement; [else statement;] Here a statement may consist of a single statement, a block of statements, or nothing. The else clause is optional. Selection Statements C supports two selection statements: if and switch. In addition, the (? :) operator is an alternative to if in certain circumstances. If The general form of the if statement is If(expression) statement; [else statement;] Here a statement may consist of a single statement, a block of statements, or nothing. The else clause is optional. October 10,

48 Session # 10 [Statements] Selection Statements If expression evaluates to true (anything other than 0), the statement or block that forms the target of if is executed, otherwise the statement after the target of else is executed, if it exists. The conditional statement controlling if must produce a scalar result. A scalar is integer, character, pointer or floating point type. If expression evaluates to true (anything other than 0), the statement or block that forms the target of if is executed, otherwise the statement after the target of else is executed, if it exists. The conditional statement controlling if must produce a scalar result. A scalar is integer, character, pointer or floating point type. October 10,

49 Session # 11 [Statements] Selection Statements If Ladder If we have several groups of statements and one of the group is to be executed selectively specify that intension by using if Ladder or switch in some cases Syntax if(expression) statement; else if(expression) statement; else if(expression) statement;. else statement; The conditions are evaluated from the top downward. As soon as a true condition is found, the statement associated with it is executed and the rest of ladder is bypassed. If none of the conditions are true, the final else is executed. If the final else is not present, no action takes place if all other conditions are false. If Ladder If we have several groups of statements and one of the group is to be executed selectively specify that intension by using if Ladder or switch in some cases Syntax if(expression) statement; else if(expression) statement; else if(expression) statement;. else statement; The conditions are evaluated from the top downward. As soon as a true condition is found, the statement associated with it is executed and the rest of ladder is bypassed. If none of the conditions are true, the final else is executed. If the final else is not present, no action takes place if all other conditions are false. October 10,

50 Session # 11 [Statements] Selection Statements switch C has a built-in multiple-branch selection statement, called switch, which successively test the value of an expression against list of integer or character constant. When a match is found, the statements associated with that constants are executed. The general form of switch statement is switch(expression) { case constant1: statement sequence [break]; case constant2: statement sequence [break]; case constant3: statement sequence [break];. [default: statement sequence;] } The expression must be evaluated to an integer type thus we can use character or integer values, but floating point expressions, for example, are not allowed. switch C has a built-in multiple-branch selection statement, called switch, which successively test the value of an expression against list of integer or character constant. When a match is found, the statements associated with that constants are executed. The general form of switch statement is switch(expression) { case constant1: statement sequence [break]; case constant2: statement sequence [break]; case constant3: statement sequence [break];. [default: statement sequence;] } The expression must be evaluated to an integer type thus we can use character or integer values, but floating point expressions, for example, are not allowed. October 10,

51 Session # 11 [Statements] Iteration Statements Iteration statements You do these things repeatedly, we can specify to the system by using one of the three repetition statements: while loop The general form is while(condition) statement; Here statement may be an empty statement, a single statement, or a block of statements. The condition may be any expression, and true is any non zero value. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line of the code immediately following the loop. Iteration statements You do these things repeatedly, we can specify to the system by using one of the three repetition statements: while loop The general form is while(condition) statement; Here statement may be an empty statement, a single statement, or a block of statements. The condition may be any expression, and true is any non zero value. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line of the code immediately following the loop. October 10,

52 Session #12 [Statements] Iteration Statements do-while loop The general form of the do-while loop is do { Statement; }while(condition); The do-while loop iterates until condition becomes false. The do-while loop checks its condition at the bottom of the loop. This means that the do-while always executes at least once. do-while loop The general form of the do-while loop is do { Statement; }while(condition); The do-while loop iterates until condition becomes false. The do-while loop checks its condition at the bottom of the loop. This means that the do-while always executes at least once. October 10,

53 Session # 12 [Statements] Iteration Statements for loop You do this things repeatedly varying so and so variable value from so and so to so with increment or decrement so and so to specify use for statement. The general form of for loop is for(Initialization; Condition; Increment) { //statements } for loop You do this things repeatedly varying so and so variable value from so and so to so with increment or decrement so and so to specify use for statement. The general form of for loop is for(Initialization; Condition; Increment) { //statements } October 10,

54 Session # 12 [C Fundamentals] Jump Statements Jump Statements C has four statements that perform an unconditional branch, You can use return and goto anywhere inside the function. You can use break and continue statements inside any of the loop statements. You can also use break with switch. return You return this value back to the calling area we can specify to the system by using return statement. The general form is below. return value / expression; break The break statement has two uses,To break the switch and the loop The general form break; Continue To opt for the early iteration use it. General form continue; Jump Statements C has four statements that perform an unconditional branch, You can use return and goto anywhere inside the function. You can use break and continue statements inside any of the loop statements. You can also use break with switch. return You return this value back to the calling area we can specify to the system by using return statement. The general form is below. return value / expression; break The break statement has two uses,To break the switch and the loop The general form break; Continue To opt for the early iteration use it. General form continue; October 10,

55 Session # 13 [Functions] Introduction to Functions Functions C’s main structural component is function. It allows compartmentalization of code and data. Functions (sub programs) are used to carry out certain sub tasks. We can divide a long C program into small blocks which can perform a certain task. Function groups a number of program statements into a unit and gives it a name. This unit can be invoked from other parts of a program. A computer program cannot handle all the tasks by it self. Instead its requests other program like entities - called functions in C - to get its tasks done. Generally in C, what are the functions we are writing other than main () function we declare them before the main(), we call them in main() and define them after main(). So function contains declaration and definition. Functions C’s main structural component is function. It allows compartmentalization of code and data. Functions (sub programs) are used to carry out certain sub tasks. We can divide a long C program into small blocks which can perform a certain task. Function groups a number of program statements into a unit and gives it a name. This unit can be invoked from other parts of a program. A computer program cannot handle all the tasks by it self. Instead its requests other program like entities - called functions in C - to get its tasks done. Generally in C, what are the functions we are writing other than main () function we declare them before the main(), we call them in main() and define them after main(). So function contains declaration and definition. October 10,

56 Session # 13 [Functions] Functions Declaration Function Declaration Function declaration syntax: returntype function_name ( parameter list); To write a function declaration easily, try to get answers for the following questions To determine maximum of two integers int max(int a, int b); Function Declaration Function declaration syntax: returntype function_name ( parameter list); To write a function declaration easily, try to get answers for the following questions To determine maximum of two integers int max(int a, int b); October 10, With what name, the function is to be identified What are the inputs it is expectingWhat type of value it is going to return

57 Session #1 3 [Functions] Functions Definition Function Definition Syntax. returntype functionname (parameter list) { /*statements*/ } Example: int max ( int a, int b) { if(a>b) return a; else return b; } Function Definition Syntax. returntype functionname (parameter list) { /*statements*/ } Example: int max ( int a, int b) { if(a>b) return a; else return b; } October 10,

58 Session #13 [Functions] Functions Call Statement Function call statement To run so and so function we can specify to the system by using function call statement. Syntax Functionname (arguments); To ask the system to run a function called max() which is expecting two integers max(10,20); When this statement is executed control goes to max () function taking arguments to the formal parameters and function executes, when function returns, return value (if any) replaces the function call statement. To receive the return value, use the following syntax. Variable=Functionname (arguments); Function call statement To run so and so function we can specify to the system by using function call statement. Syntax Functionname (arguments); To ask the system to run a function called max() which is expecting two integers max(10,20); When this statement is executed control goes to max () function taking arguments to the formal parameters and function executes, when function returns, return value (if any) replaces the function call statement. To receive the return value, use the following syntax. Variable=Functionname (arguments); October 10,

59 Session # 13 [Functions] Types of Call Statements Call By Value and Call By Address In a computer language there are two ways to pass the arguments to a function; the first one is call by value. This method copies the value of the argument into the formal parameter of the function. In this case, changes made to the parameter have no effect on the argument. ex: void ssit (int, int); Call by Address is second way of passing the arguments to the function. In this method the address of the argument will be copied to the formal parameters. In side the function,the address is used to access the actual argument used in the call. This means that the changes made to the parameter effect to the argument ex: void ssit (int *,int *); Call By Value and Call By Address In a computer language there are two ways to pass the arguments to a function; the first one is call by value. This method copies the value of the argument into the formal parameter of the function. In this case, changes made to the parameter have no effect on the argument. ex: void ssit (int, int); Call by Address is second way of passing the arguments to the function. In this method the address of the argument will be copied to the formal parameters. In side the function,the address is used to access the actual argument used in the call. This means that the changes made to the parameter effect to the argument ex: void ssit (int *,int *); October 10,

60 Session #1 3 [Functions] Example Program using Function #include int max(int,int,int); void main(void) { int m,n,o,big; clrscr(); printf("enter any three nos. one by one\n"); scanf("%d%d%d",&m,&n,&o); printf("\n m = %d and n = %d and o = %d",m,n,o); big=max(m,n,o); printf("\n maximum is :%d:“,big); getche(); } int max(int x,int y,int z) { return x > y && x > z ? x : y > z ? y : z; } #include int max(int,int,int); void main(void) { int m,n,o,big; clrscr(); printf("enter any three nos. one by one\n"); scanf("%d%d%d",&m,&n,&o); printf("\n m = %d and n = %d and o = %d",m,n,o); big=max(m,n,o); printf("\n maximum is :%d:“,big); getche(); } int max(int x,int y,int z) { return x > y && x > z ? x : y > z ? y : z; } October 10,

61 Session # 14 [Arrays and Strings] Introduction 2 Arrays Arrays An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. That means that, for example, we can store 5 values of type int in an array without having to declare 5 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type[int] with a unique identifier. These similar elements could be all integers or all floats or all characters etc. Usually, the array of characters is called a "string", where as an array of integers or floats are called simply an array. Moreover we can construct one dimensional array as well as multidimensional array. Arrays An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. That means that, for example, we can store 5 values of type int in an array without having to declare 5 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type[int] with a unique identifier. These similar elements could be all integers or all floats or all characters etc. Usually, the array of characters is called a "string", where as an array of integers or floats are called simply an array. Moreover we can construct one dimensional array as well as multidimensional array. October 10,

62 Session # 14 [Arrays and Strings] One Dimensional Arrays One Dimensional Array It is an array that stores values in the memory horizontally. Array declaration: To construct a one dimensional array system requires the following 3 specifications, they include. One Dimensional Array It is an array that stores values in the memory horizontally. Array declaration: To construct a one dimensional array system requires the following 3 specifications, they include. October 10, Array name (group name)Number of values you want to have in that group.Type of values you want to have in that group.

63 Session # 14 [Arrays and Strings] One Dimensional Arrays Syntax Type ArrayVariableName [size]; eg: int nos [5]; when above statement is executed, memory will be allocated to store 5 integers in continuous locations nos The amount of storage required to hold an array is directly related to its type and size, for a single dimensional array the total size in bytes will be computed as total bytes=sizeof(base type)* size of an array. Total number of bytes allotted for this array are: sizeof(int) * 5 => 2 * 5 = 10; Syntax Type ArrayVariableName [size]; eg: int nos [5]; when above statement is executed, memory will be allocated to store 5 integers in continuous locations nos The amount of storage required to hold an array is directly related to its type and size, for a single dimensional array the total size in bytes will be computed as total bytes=sizeof(base type)* size of an array. Total number of bytes allotted for this array are: sizeof(int) * 5 => 2 * 5 = 10; October 10,

64 Session # 14 [Arrays and Strings] One Dimensional Arrays Accessing array elements: Each element is identifying with unique index value. Indexing is zero based. First element index is 0, second element index is 1, so on. To name the element of the array syntax is Arrayname [index] Name of the first element is nos[0],name of the second is nos[1],so on. While constructing the array, if we know what values elements are to represent, use the following syntax. type arrayvariable[size] ={list of values}; int nos[]={10,20,30,40,50} ; Reading values into Array elements: for example, to read values from the keyboard to the array that above declared, do the following for (i=0; i< size; i++) scanf(“%d”,&nos[i]); Accessing array elements: Each element is identifying with unique index value. Indexing is zero based. First element index is 0, second element index is 1, so on. To name the element of the array syntax is Arrayname [index] Name of the first element is nos[0],name of the second is nos[1],so on. While constructing the array, if we know what values elements are to represent, use the following syntax. type arrayvariable[size] ={list of values}; int nos[]={10,20,30,40,50} ; Reading values into Array elements: for example, to read values from the keyboard to the array that above declared, do the following for (i=0; i< size; i++) scanf(“%d”,&nos[i]); October 10,

65 Session # 15 [Arrays and Strings] Two Dimensional Arrays Two-Dimensional Array C supports multi dimensional arrays. The simplest form of multidimensional array is the two dimensional array. A two dimensional array is essentially, an array of one dimensional arrays. To declare two dimensional array syntax is type arrayname[m][n]; Example: int twod[4][3]; To access the element of two dimensional array arrayname[i][j]; To assign 1 in first element twod[0][0]=1; In case of two dimensional arrays, the following formula yields the number of bytes of memory needed to hold it. Bytes=sizeof(firstindex) * sizeof(secondindex) * sizeof (base type) Two-Dimensional Array C supports multi dimensional arrays. The simplest form of multidimensional array is the two dimensional array. A two dimensional array is essentially, an array of one dimensional arrays. To declare two dimensional array syntax is type arrayname[m][n]; Example: int twod[4][3]; To access the element of two dimensional array arrayname[i][j]; To assign 1 in first element twod[0][0]=1; In case of two dimensional arrays, the following formula yields the number of bytes of memory needed to hold it. Bytes=sizeof(firstindex) * sizeof(secondindex) * sizeof (base type) October 10,

66 Session # 16 [Pointers] Introduction to Pointers Pointers A pointer is a variable that holds memory address. This address is the location of another variable in memory. Correct understanding and use of pointers is crucial to successful c programming, there are several reasons for this: Pointers A pointer is a variable that holds memory address. This address is the location of another variable in memory. Correct understanding and use of pointers is crucial to successful c programming, there are several reasons for this: October 10, Pointers can improve the efficiency of certain routines. Pointers provide the means by which function can modify their calling arguments. Pointers support dynamic allocation and dynamic data structures such as binary trees and linked lists

67 Session # 16 [Pointers] Pointer Variables Pointer variables A pointer is a variable that holds a memory address. A variable is going to be a pointer, it must be declared as such type * variablename ; Example: int * p; Here type is the base type of the pointer. Sample program using pointer operators: int a=15,*p; p p=&a; printf(“ a=%d”,*p); a 201 Pointer variables A pointer is a variable that holds a memory address. A variable is going to be a pointer, it must be declared as such type * variablename ; Example: int * p; Here type is the base type of the pointer. Sample program using pointer operators: int a=15,*p; p p=&a; printf(“ a=%d”,*p); a 201 October 10,

68 Session # 17 [Pointers] Pointer Arithmetic Pointer Arithmetic There are only two arithmetic operations that can use on pointers, they are 1. Addition 2. Subtraction To understand what occurs in pointer arithmetic, Let p1 be an integer pointer with the address Also assume int ‘s are 2 bytes long. After the expression : P1++; P1 contains 2002, not The reason for this is that each time p1 is incremented it will point to the next integer. The same is true for decrements. Each time a pointer is incremented, it points to the memory location of the next element of its base type. Each time it is decremented it points to the memory location of the previous element. Subtracting one pointer from other, in order to find number of objects of base type that separate the two pointers. Note: all other arithmetic operations are prohibited. Pointer Arithmetic There are only two arithmetic operations that can use on pointers, they are 1. Addition 2. Subtraction To understand what occurs in pointer arithmetic, Let p1 be an integer pointer with the address Also assume int ‘s are 2 bytes long. After the expression : P1++; P1 contains 2002, not The reason for this is that each time p1 is incremented it will point to the next integer. The same is true for decrements. Each time a pointer is incremented, it points to the memory location of the next element of its base type. Each time it is decremented it points to the memory location of the previous element. Subtracting one pointer from other, in order to find number of objects of base type that separate the two pointers. Note: all other arithmetic operations are prohibited. October 10,

69 Session # 17 [Pointers] Arrays with Pointers Arrays with Pointers we are already familiar with arrays(collection of similar data elements referred through common name).Processing array with pointers is much more effective and it is very simple, because generally all data elements of an array are stored in continuous memory locations, so if you know address of starting element of an array, it is very easy to move till the end. Finding address of the first element of an array is simple, as like getting the address of any (by prefixing & to that variable). Here in our arrays each element can name as Arrayname [index]; First element index is 0, so the first element name is Arrayname [0]; so & Arrayname [0];(address of first element) int a[10],*p;( 'a' be the array and 'p' is the pointer). p=&a[0]; we can write p=a; (Because Arrayname itself contains address of first element ) Arrays with Pointers we are already familiar with arrays(collection of similar data elements referred through common name).Processing array with pointers is much more effective and it is very simple, because generally all data elements of an array are stored in continuous memory locations, so if you know address of starting element of an array, it is very easy to move till the end. Finding address of the first element of an array is simple, as like getting the address of any (by prefixing & to that variable). Here in our arrays each element can name as Arrayname [index]; First element index is 0, so the first element name is Arrayname [0]; so & Arrayname [0];(address of first element) int a[10],*p;( 'a' be the array and 'p' is the pointer). p=&a[0]; we can write p=a; (Because Arrayname itself contains address of first element ) October 10,

70 Session # 17 [Pointers] Arrays with Pointers Arrays with Pointers Once u know address of first element it’s very easy to move forward, thru pointer addition. At the same time we can move from last element to first also, thru pointer subtraction from last element address. Example: int a[5]={20,30,40,10,50}, *p; p=a; /* suppose address is 2000*/ The base address value is obtained by mentioning its name first value can be accessed by using *p.similarly we can access next elements by *(p + i). Arrays with Pointers Once u know address of first element it’s very easy to move forward, thru pointer addition. At the same time we can move from last element to first also, thru pointer subtraction from last element address. Example: int a[5]={20,30,40,10,50}, *p; p=a; /* suppose address is 2000*/ The base address value is obtained by mentioning its name first value can be accessed by using *p.similarly we can access next elements by *(p + i). October 10,

71 Session # 17 [Arrays and Strings] Arrays with Functions Passing One Dimensional Array to Functions In C, you can not pass an entire array as an argument to function, However You can pass a pointer to an array by specifying arrays name with out an index. For example the following program fragment passes the address of nos to display(). int main(void) { int nos[]={10,20,30,40,50}; display(nos); return 0; } If a function receives a pointer to a one dimensional array, you can declare its formal parameter in one of three ways: as a pointer, as a sized array or as unsized array. For example, to receive nos, function called display() it can be defined as Passing One Dimensional Array to Functions In C, you can not pass an entire array as an argument to function, However You can pass a pointer to an array by specifying arrays name with out an index. For example the following program fragment passes the address of nos to display(). int main(void) { int nos[]={10,20,30,40,50}; display(nos); return 0; } If a function receives a pointer to a one dimensional array, you can declare its formal parameter in one of three ways: as a pointer, as a sized array or as unsized array. For example, to receive nos, function called display() it can be defined as October 10,

72 Session #17 [Arrays and Strings] Arrays with Functions Passing One Dimensional Array to Functions All three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received Passing One Dimensional Array to Functions All three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received October 10, Pointer version void display(int *p) { int k; for(k=0;k<5; k++) printf(“%d “,*(p+k)); } Sized array version void display(int p[5]) { int k; for(k=0;k<5; k++) printf(“%d “,p[k]); } Un sized array version void display(int p[]) { int k; for(k=0;k<5; k++) printf(“%d “,p[k]); }

73 Session # 18 [Arrays and Strings] Strings Strings Some thing which is placed in between double quotation marks is called string literal.In C a string is treated as one dimensional char array terminated with null character. This means that after the last truly usable char there is a null, hex 00, which is represented in C by '\0'. Example: char str[15],*p; p=str; // similar to p=& str[0],bcz array name itself contains first element address. The above statement declares a char array called str. C provides fifteen consecutive bytes of memory. Only the first fourteen bytes are usable for character storage, because one must be used for the string-terminating null The following is a representation of what would be in RAM, if the string "Hello, world!" is stored in this array. Strings Some thing which is placed in between double quotation marks is called string literal.In C a string is treated as one dimensional char array terminated with null character. This means that after the last truly usable char there is a null, hex 00, which is represented in C by '\0'. Example: char str[15],*p; p=str; // similar to p=& str[0],bcz array name itself contains first element address. The above statement declares a char array called str. C provides fifteen consecutive bytes of memory. Only the first fourteen bytes are usable for character storage, because one must be used for the string-terminating null The following is a representation of what would be in RAM, if the string "Hello, world!" is stored in this array. October 10, charactersHellO,world!\0 Hex values48656c 6f2c20776f716c subscripts

74 Session # 18 [Arrays & Strings] String Functions Built in String Functions The string functions operate on null-terminated arrays of characters and require the header strlen() Syntax: size_t strlen( char *str ); The strlen() function returns the length of str (determined by the number of characters before null termination). The following code will result in len having the value 13. int len = strlen("Hello, world!"); strcpy() Syntax: char *strcpy( char *to, const char *from ); The strcpy() function copies characters in the string from to the string to, including the null termination. Given the following declarations, several things are possible. char S[25],D[25]; Copying a whole string from S to D: strcpy (D, S); Copying the tail end of string S to D: strcpy( D, &S[8]); Note. If you fail to ensure that the source string is null-terminated, very strange and sometimes very ugly things may result. Built in String Functions The string functions operate on null-terminated arrays of characters and require the header strlen() Syntax: size_t strlen( char *str ); The strlen() function returns the length of str (determined by the number of characters before null termination). The following code will result in len having the value 13. int len = strlen("Hello, world!"); strcpy() Syntax: char *strcpy( char *to, const char *from ); The strcpy() function copies characters in the string from to the string to, including the null termination. Given the following declarations, several things are possible. char S[25],D[25]; Copying a whole string from S to D: strcpy (D, S); Copying the tail end of string S to D: strcpy( D, &S[8]); Note. If you fail to ensure that the source string is null-terminated, very strange and sometimes very ugly things may result. October 10,

75 Session # 18 [Arrays & Strings] String Functions Built in String Functions strcat() Syntax: char *strcat( char *str1, const char *str2 ); The strcat() function concatenates str2 onto the end of str1, and returns str1. For example: printf( "Enter your name: " ); scanf( "%s", name ); title = strcat( name, " the Great" ); printf( "Hello, %s\n", title ); strncat() Syntax: char *strncat( char *str1, const char *str2, size_t count ); The function strncat() concatenates at most count characters of str2 onto str1, adding a null termination. The resulting string is returned. Given the following declarations, several things are possible, but only one is commonly used. char S[25] = "world!“,D[25]=“Hello,”; Concatenating five characters from the beginning of S onto the end of D and placing a null at the end: strncat(D, S, 5); [strncat(D, S, strlen(S) -1);] Both would result in D containing "Hello, world". Built in String Functions strcat() Syntax: char *strcat( char *str1, const char *str2 ); The strcat() function concatenates str2 onto the end of str1, and returns str1. For example: printf( "Enter your name: " ); scanf( "%s", name ); title = strcat( name, " the Great" ); printf( "Hello, %s\n", title ); strncat() Syntax: char *strncat( char *str1, const char *str2, size_t count ); The function strncat() concatenates at most count characters of str2 onto str1, adding a null termination. The resulting string is returned. Given the following declarations, several things are possible, but only one is commonly used. char S[25] = "world!“,D[25]=“Hello,”; Concatenating five characters from the beginning of S onto the end of D and placing a null at the end: strncat(D, S, 5); [strncat(D, S, strlen(S) -1);] Both would result in D containing "Hello, world". October 10,

76 Session # 19 [Arrays & Strings] String Functions Built in String Functions strcmp() The function strcmp() compares str1 and str2 Syntax: int strcmp( const char *str1, const char *str2 ); For example: printf( "Enter your name: " ); scanf( "%s", name ); if( strcmp( name, "Mary" ) == 0 ) printf( "Hello, Dr. Mary!\n" ); strncmp() Syntax: int strncmp( const char *str1, const char *str2, size_t count ); The strncmp() compares at most count characters of str1 and str2. The return value is as follows(even strcmp() returns the same): If there are less than count characters in either string, then the comparison will stop after the first null termination is encountered. Built in String Functions strcmp() The function strcmp() compares str1 and str2 Syntax: int strcmp( const char *str1, const char *str2 ); For example: printf( "Enter your name: " ); scanf( "%s", name ); if( strcmp( name, "Mary" ) == 0 ) printf( "Hello, Dr. Mary!\n" ); strncmp() Syntax: int strncmp( const char *str1, const char *str2, size_t count ); The strncmp() compares at most count characters of str1 and str2. The return value is as follows(even strcmp() returns the same): If there are less than count characters in either string, then the comparison will stop after the first null termination is encountered. October 10, Return value Explanation less than 0str1 is less than str2 equal to 0str1 is equal to str2 greater than 0str1 is greater than str2

77 Session # 20[DMA] Introduction to DMA Dynamic memory allocation: C’s Memory Map A complied C program creates and uses four logically distinct regions of memory. stack heap Dynamic memory allocation: C’s Memory Map A complied C program creates and uses four logically distinct regions of memory. stack heap October 10,

78 Session #20 [DMA] DMA Functions Dynamic memory allocation: The process of allocating memory at run time is known as dynamic memory allocation. Although c does not inherently have this facility there are four library routines which allow this function. Standard C defines four dynamic allocation functions that all compilers will support[associated with stdlib.h ], those are.. Dynamic memory allocation: The process of allocating memory at run time is known as dynamic memory allocation. Although c does not inherently have this facility there are four library routines which allow this function. Standard C defines four dynamic allocation functions that all compilers will support[associated with stdlib.h ], those are.. October 10, calloc() void *calloc( size_t num, size_t size ); returns a pointer to space for an array of num objects, each of size size. calloc() returns NULL if there is an error malloc() void *malloc( size_t size ); returns a pointer to a chunk of memory of size size, or NULL if there is an error. The memory pointed to will be on the heap, not the stack, so make sure to free it when you are done with it realloc() void *realloc( void *ptr, size_t size ); changes the size of the object pointed to by ptr to the given size. size can by any size, larger or smaller than the original. The return value is a pointer to the new space, or NULL if there is an error. Free() void free( void *ptr); deallocates the space pointed to by ptr, freeing it up for future use. ptr must have been used in a previous call to malloc(), calloc(), or realloc().

79 Session # 21 [Derived Types] Introduction to Derived Data Types Derived Types C language gives you five ways to create a custom data types, those are.. Derived Types C language gives you five ways to create a custom data types, those are.. October 10,

80 Session # 21 [Derived Types] Structures Structures A structure is a collection of variables referenced under one name, providing a convenient means of keeping related information together. A structure declaration forms a template that can be used to create structured objects. The variables that make up the structure are called members. They are also commonly refer to as elements or to as fields. Need of structure How will you store the address of a person which consists of name, street, city, state, pin with the following types char name[20] char street[20] char city[20] char state[3] unsigned long int pin The above stated address will be created in 5 locations which may not be side-by-side,to store all the variables of a particular data in consecutive locations of memory there is a need for new data type. i.e STRUCTURE Structures A structure is a collection of variables referenced under one name, providing a convenient means of keeping related information together. A structure declaration forms a template that can be used to create structured objects. The variables that make up the structure are called members. They are also commonly refer to as elements or to as fields. Need of structure How will you store the address of a person which consists of name, street, city, state, pin with the following types char name[20] char street[20] char city[20] char state[3] unsigned long int pin The above stated address will be created in 5 locations which may not be side-by-side,to store all the variables of a particular data in consecutive locations of memory there is a need for new data type. i.e STRUCTURE October 10,

81 Session # 21 [Derived Types] Structures Structure Features Structure allows us to keep related variables under one name This type object allows us to keep related information together The General form a structure declaration is Note: Here either tag or structure-variables may be omitted, but not both. Structure Features Structure allows us to keep related variables under one name This type object allows us to keep related information together The General form a structure declaration is Note: Here either tag or structure-variables may be omitted, but not both. October 10, struct tag { type member-name;. } structure-variables;

82 Session # 21 [Derived Types] Structure Examples Structure Examples October 10, Student Address Details struct Addr { char name[20]; char street[20; char city[20]; char state[3]; unsigned long int pin; }; Department Details struct dept { int deptno; char name[20]; char location[20]; }; Box Details struct Box { double width; double height; double depth; };

83 Session # 22 [Derived Types] Constructing the structure objects Constructing the structure objects To use the Structure we need to construct structure object, we have created the following different variables A simple variable A pointer variable A simple array variable An array of pointers In the same way we can create a structure type variable sysntax: struct ; Eaxmple: To declare variable of type addr, write struct addr addr_info; When above statement is executed for all members memory locations are allocated as per their specifications in a continuous manner. Constructing the structure objects To use the Structure we need to construct structure object, we have created the following different variables A simple variable A pointer variable A simple array variable An array of pointers In the same way we can create a structure type variable sysntax: struct ; Eaxmple: To declare variable of type addr, write struct addr addr_info; When above statement is executed for all members memory locations are allocated as per their specifications in a continuous manner. October 10,

84 Session # 22 [Derived Types] Structure Processing Accessing structure members Individual members of a structure are accessed through the use of the “.” (dot) Operator. The general form for accessing the member of the structure is objectname.membername For Example, the following statement assigns the pin code to the pin field of the structure variable addr_info. addr_info.pin=500036; Structure Memory Allocation Structure object occupies the memory as “total no. of bytes occupied by all the members of the structure” Consider Student address structure struct addr { char name[20]; char street[20]; char city[20]; char state[3]; unsigned long int pin; }; The total memory allocated for this structure is = 67 bytes Accessing structure members Individual members of a structure are accessed through the use of the “.” (dot) Operator. The general form for accessing the member of the structure is objectname.membername For Example, the following statement assigns the pin code to the pin field of the structure variable addr_info. addr_info.pin=500036; Structure Memory Allocation Structure object occupies the memory as “total no. of bytes occupied by all the members of the structure” Consider Student address structure struct addr { char name[20]; char street[20]; char city[20]; char state[3]; unsigned long int pin; }; The total memory allocated for this structure is = 67 bytes October 10,

85 Session # 22 [Derived Types] Structure Example Program #include #include struct addr { char name[20],street[20],city[20]; unsigned long pin ; }; struct addr addr_info; int main(void) { clrscr(); printf(“Enter Name”); gets(addr_info.name); printf(“Enter Street”); gets(addr_info.street); printf(“Enter City”); gets(addr_info.city); printf(“Enter State”); gets(addr_info.state); printf(“Enter Pin”); scanf(“%d”,addr_info.pin); printf(“Name:%s\n”,addr_info.name); printf(“street:%s\n”,addr_info.street); printf(“city:%s\n”,addr_info.city); printf(“state:%s\n”,addr_info.state); printf(“pin:%d\n”,addr_info.pin); return 0; } #include #include struct addr { char name[20],street[20],city[20]; unsigned long pin ; }; struct addr addr_info; int main(void) { clrscr(); printf(“Enter Name”); gets(addr_info.name); printf(“Enter Street”); gets(addr_info.street); printf(“Enter City”); gets(addr_info.city); printf(“Enter State”); gets(addr_info.state); printf(“Enter Pin”); scanf(“%d”,addr_info.pin); printf(“Name:%s\n”,addr_info.name); printf(“street:%s\n”,addr_info.street); printf(“city:%s\n”,addr_info.city); printf(“state:%s\n”,addr_info.state); printf(“pin:%d\n”,addr_info.pin); return 0; } October 10,

86 Session # 23 [Derived Types] Array of structures Array of structures As we know array is collection of similar data types like int, float, char etc. In the same way we can also define array of structures. In that array every element is of structure type. Array of structures can be declared as follows. struct addr { char name[20]; char street[20]; char city[25]; char state[3]; unsigned long pin ; }; struct addr addr_info[5]; Array of structures As we know array is collection of similar data types like int, float, char etc. In the same way we can also define array of structures. In that array every element is of structure type. Array of structures can be declared as follows. struct addr { char name[20]; char street[20]; char city[25]; char state[3]; unsigned long pin ; }; struct addr addr_info[5]; October 10,

87 Session #23 [Derived Types] Nested structures Structure within structure (Nested Structure) We can take any data type for declaring structure members like int, float, char etc.we can also take objects of one structure as members of another structure. The general form is struct date { int dd; int mm; int yy; }; example Struct person { char name[25]; struct date dob; }emp; We can access the dd as emp.dod.dd Structure within structure (Nested Structure) We can take any data type for declaring structure members like int, float, char etc.we can also take objects of one structure as members of another structure. The general form is struct date { int dd; int mm; int yy; }; example Struct person { char name[25]; struct date dob; }emp; We can access the dd as emp.dod.dd October 10,

88 Session # 23 [Derived Types] Passing Structure object to functions Passing Structure object to functions Like variables of standard type, structure variables can also be passed to the function by value or address. Syntax: return type function name (structure variable) { stmts;. } Example: void show ( struct record m) { } Passing Structure object to functions Like variables of standard type, structure variables can also be passed to the function by value or address. Syntax: return type function name (structure variable) { stmts;. } Example: void show ( struct record m) { } October 10,

89 Session # 23 [Derived Types] Pointer to a STRUCTURE Pointer to a STRUCTURE Pointer is a variable that holds the address of another variable. The variable may be of any type int, float, char etc. in the same way we can define a pointer to a structure. Structure pointers are declared by placing * in front of structure variables name. Example: struct addr { char name[20]; char street[20]; char city[25]; char state[3]; unsigned long pin ; }; struct addr *p; (p is pointer to structure.) To access the member of a structure using pointer to the structure we must use  (arrow) operator As Pointer name  member name For Example, to assign to pin p->pin= Pointer to a STRUCTURE Pointer is a variable that holds the address of another variable. The variable may be of any type int, float, char etc. in the same way we can define a pointer to a structure. Structure pointers are declared by placing * in front of structure variables name. Example: struct addr { char name[20]; char street[20]; char city[25]; char state[3]; unsigned long pin ; }; struct addr *p; (p is pointer to structure.) To access the member of a structure using pointer to the structure we must use  (arrow) operator As Pointer name  member name For Example, to assign to pin p->pin= October 10,

90 Session # 24 [Derived Types] Enumerations Enumerations Enumeration is a set of named integer constants. Enumerations are defined much like structures. The keyword enum the start of the enumeration type. The general form for enumerations is Syntax enum tag{ //Enumeration list } var_list; The following four fragments define an enumeration called coin: enum coin { penny, nickel, dime, quarter, half_dollar, dollar }; The enumeration tagname can be used to declare variables of its type the following declare money to be a variable of type coin: enum coin money; if(money==quarter) printf (“Money is a quarter.\n”); The key point to understand about is the enumeration is that each of the symbols stands for an integer value. Each symbol is given a value one greater than the symbol that precedes it. The value of the first enumeration symbol is zero. Therefore, printf (“%d %d “,penny, dime); [ o/p : 0 2] Enumerations Enumeration is a set of named integer constants. Enumerations are defined much like structures. The keyword enum the start of the enumeration type. The general form for enumerations is Syntax enum tag{ //Enumeration list } var_list; The following four fragments define an enumeration called coin: enum coin { penny, nickel, dime, quarter, half_dollar, dollar }; The enumeration tagname can be used to declare variables of its type the following declare money to be a variable of type coin: enum coin money; if(money==quarter) printf (“Money is a quarter.\n”); The key point to understand about is the enumeration is that each of the symbols stands for an integer value. Each symbol is given a value one greater than the symbol that precedes it. The value of the first enumeration symbol is zero. Therefore, printf (“%d %d “,penny, dime); [ o/p : 0 2] October 10,

91 Session # 24 [Derived Types] Unions Unions A union is a collection of variables of different types, just like a structure. However, with unions, you can only store information in one field at any one time. Once a new value is assigned to a field, the existing data is wiped over with the new data. The size of a union is equal to the size of it's largest data member. why because only one member can be used at a time Syntax to declare a union: Unions A union is a collection of variables of different types, just like a structure. However, with unions, you can only store information in one field at any one time. Once a new value is assigned to a field, the existing data is wiped over with the new data. The size of a union is equal to the size of it's largest data member. why because only one member can be used at a time Syntax to declare a union: October 10, union tag { type member-name;. } variables;

92 Session # 24 [Derived Types] Unions Unions ACCESSING UNION FIELDS To access the fields of a union, use the dot operator(.) just as you would for a structure. Example: union data { int x; float f; } myData; int main() { myData.x = 42; printf("Here is the Data:\n%i\n%.3f\n”,myData.x, myData.f ); myData.f = ; printf("Here is the Data:\n%i\n%.3f\n“, myData.x, myData.f ); } Unions ACCESSING UNION FIELDS To access the fields of a union, use the dot operator(.) just as you would for a structure. Example: union data { int x; float f; } myData; int main() { myData.x = 42; printf("Here is the Data:\n%i\n%.3f\n”,myData.x, myData.f ); myData.f = ; printf("Here is the Data:\n%i\n%.3f\n“, myData.x, myData.f ); } October 10,

93 Session # 25 [Pre Processor Directives] I ntroduction to Pre Processor Directives Preprocessing Occurs before a program is compiled Inclusion of other files Definition of symbolic constants and macros – Format of preprocessor directives Lines begin with # Only whitespace characters before directives on a line #include Preprocessor Directive ( Copy a specified file included in place of the directive ): used for Programs with multiple source files to be compiled together Preprocessing Occurs before a program is compiled Inclusion of other files Definition of symbolic constants and macros – Format of preprocessor directives Lines begin with # Only whitespace characters before directives on a line #include Preprocessor Directive ( Copy a specified file included in place of the directive ): used for Programs with multiple source files to be compiled together October 10, Use and Searches standard library for file #include Searches current directory, then standard library Use for user-defined files #include "filename"

94 Session # 35 [Pre Processor Directives] I ntroduction to Pre Processor Directives #define Preprocessor Directive ( Preprocessor directive used to create symbolic constants and macros – Symbolic constants ): When program compiled, all occurrences of symbolic constant or macro replaced with replacement text Format: #define identifier replacement-text Example: #define PI – Everything to right of identifier replaces text Replaces “ PI ” with " = “ Note : Cannot redefine symbolic constants once they have been created #define Preprocessor Directive ( Preprocessor directive used to create symbolic constants and macros – Symbolic constants ): When program compiled, all occurrences of symbolic constant or macro replaced with replacement text Format: #define identifier replacement-text Example: #define PI – Everything to right of identifier replaces text Replaces “ PI ” with " = “ Note : Cannot redefine symbolic constants once they have been created October 10,

95 Session # 25 [Pre Processor Directives] I ntroduction to Pre Processor Directives Macros A macro without arguments is treated like a symbolic constant A macro with arguments has its arguments substituted for replacement text, when the macro is expanded  Performs a text substitution  No data type checking Macro Examples Macros A macro without arguments is treated like a symbolic constant A macro with arguments has its arguments substituted for replacement text, when the macro is expanded  Performs a text substitution  No data type checking Macro Examples October 10, Macro definitionMacro callReplacement form #define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) )area = CIRCLE_AREA( 4 );area = ( * (4) * (4)); ‘’area = CIRCLE_AREA( c + 2 );area= * (c + 2) * (c +2); #define RECT_AREA(x, y) ((x)*(y))area=RECT_AREA((a+4),(b+7));area = ( ( a + 4 ) * ( b + 7 ) );

96 Session #26 [File I/O] Introduction to File I/O C File I/O and Binary File I/O When accessing files through C, the first necessity is to have a way to access the files. For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. (You can think of it as the memory address of the file or the location of the file). example: FILE *fp; To open a file you need to use the fopen function, which returns a FILE pointer. Once you've opened a file, you can use the FILE pointer to let the compiler perform input and output functions on the file. FILE *fopen(const char *filename, const char *mode); The modes are… C File I/O and Binary File I/O When accessing files through C, the first necessity is to have a way to access the files. For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. (You can think of it as the memory address of the file or the location of the file). example: FILE *fp; To open a file you need to use the fopen function, which returns a FILE pointer. Once you've opened a file, you can use the FILE pointer to let the compiler perform input and output functions on the file. FILE *fopen(const char *filename, const char *mode); The modes are… October 10, symbolfunctionalitymodefunctionality r open for reading r+ open for reading and writing, start at beginning w open for writing (file need not exist) w+open for reading and writing (overwrite file) a open for appending (file need not exist) a+open for reading and writing (append if file exists)

97 Session #26 [File I/O] File Process Example of using fopen: FILE *fp;fp=fopen("c:\\test.txt", "r"); [open test.txt for reading in text mode] To close a function you can use the function int fclose(FILE *a_file); [returns zero if the file is closed successfully ] Example of fclose : fclose(fp); you can use fprintf and fscanf,to working with text I/O and they are similar to their friends printf and scanf except that you must pass the FILE pointer as first argument. Example: FILE *fp; fp=fopen("c:\\test.txt", "w"); fprintf(fp, "Testing...\n"); fgetc(): [read a single character from a file] int fgetc (FILE *fp); fputc(): [write a character at a time into a file ] int fputc( int c, FILE *fp ); Example of using fopen: FILE *fp;fp=fopen("c:\\test.txt", "r"); [open test.txt for reading in text mode] To close a function you can use the function int fclose(FILE *a_file); [returns zero if the file is closed successfully ] Example of fclose : fclose(fp); you can use fprintf and fscanf,to working with text I/O and they are similar to their friends printf and scanf except that you must pass the FILE pointer as first argument. Example: FILE *fp; fp=fopen("c:\\test.txt", "w"); fprintf(fp, "Testing...\n"); fgetc(): [read a single character from a file] int fgetc (FILE *fp); fputc(): [write a character at a time into a file ] int fputc( int c, FILE *fp ); October 10,

98 Session #26 [File I/O] Binary Files Binary I/O [ fread(),fwrite() ] These are dealing with blocks of memories - usually arrays. Because they accept pointers, you can also use these functions with other data structures; you can even write structs to a file or a read struct into memory. Declarations : size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file); size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file); Example: FILE *fp; fp=fopen("c:\\test.bin", "wb"); char x[10]="ABCDEFGHIJ"; fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp); Binary I/O [ fread(),fwrite() ] These are dealing with blocks of memories - usually arrays. Because they accept pointers, you can also use these functions with other data structures; you can even write structs to a file or a read struct into memory. Declarations : size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file); size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file); Example: FILE *fp; fp=fopen("c:\\test.bin", "wb"); char x[10]="ABCDEFGHIJ"; fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp); October 10,

99 Session #27 [ C Standard Library] math.h October 10,

100 Session #27 [ C Standard Library] ctype.h October 10,

101 Session # 27[ C Standard Library] stdlib.h October 10,


Download ppt "Session # 2 [Introduction to Computers] What is Computer ? A computer is a machine that manipulates data according to a list of instructions. Machine."

Similar presentations


Ads by Google