Presentation is loading. Please wait.

Presentation is loading. Please wait.

Unit-III C Programming

Similar presentations


Presentation on theme: "Unit-III C Programming"— Presentation transcript:

1 Unit-III C Programming
Prof. N. B. Pokale

2 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Syllabus C programming Character set, constants, variables, keywords comments Operators and operator precedence Statements, I/O operations, preprocessor directives Pointers, arrays and strings User Defined data types: structure and union Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

3 Introduction to Programming Languages
Computer programming language can be classified into two major categories Low level languages Machine Language Assembly Language High level languages FORTRAN, COBOL, BASIC, PASCAL, ADA, LISP, C. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

4 Overview of ‘C’ Language
History of ‘C’ Language C was developed at Bell Laboratories in 1972 by Dennis Ritchie Many of its principles and ideas were taken from the earlier language B and B's earlier ancestors BCPL and CPL. C is a powerful, flexible language that provides fast program execution and imposes few constraints on the programmer. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

5 Graphical Representation of History of C
1960 ALGOL International group 1967 BCPL Martin Richards 1970 B Ken Thompson 1972 Traditional C Dennis Ritchie 1978 K & R C Kernighan and Ritchie 1989 ANSI C ANSI Committee 1990 ANSI/ISO C ISO Committee 1999 C99 Standardization Committee Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

6 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Uses of C Language compilers and interpreters Device drivers Telecom applications Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

7 The Edit-Compile-Run Loop
Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

8 Steps in the compilation and execution process
Input Program Output source code > Preprocessor > expanded source code expanded source code > Compiler > assembly source code assembly code > Assembler > object code object code > Linker > executable code executable code > Loader > execution Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

9 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Identifier Identifier is the name of a variable that is made up from combination of alphabets, digits and underscore. Variable t is a data name which is used to store data and may change during program execution. It is opposite to constant. Variable name is a name given to memory cells location of a computer where data is stored. Rules for variables First character should be letter or alphabet. Keywords are not allowed to use as a variable name. White space is not allowed. C is case sensitive i.e. UPPER and lower case are significant. Only underscore, special symbol is allowed between two characters. The length of identifier may be upto 31 characters but only the first 8 characters are significant by compiler. (Note: Some compilers allow variable names whose length may be upto 247 characters. But, it is recommended to use maximum 31 characters in variable name. Large variable name leads to occur errors.) Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

10 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
The C Character Set A character refers to the digit, alphabet or special symbol used to data representation. Alphabets :                 A-Z, a-z Digits :                       0-9 Special Characters :    ~ # $ % ^ & * ( ) _ + { } [ ] - < > , . / ? \ | : ; " ' White Spaces :            Horizontal tab, Carriage return, New line, form feed Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

11 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Keywords Keywords are the system defined identifiers. All keywords have fixed meanings that do not change. White spaces are not allowed in keywords. Keyword may not be used as an identifier. It is strongly recommended that keywords should be in lower case letters. There are 32 keywords in C int float double long short signed unsigned const if else switch break default do while for register extern static struct typedef enum return sizeof goto union auto case void char continue volatile Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

12 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Escape Sequence Characters (Backslash Character Constants) in C  supports some special escape sequence characters that are used to do special tasks. These are also called as 'Backslash characters'. Character Constant Meaning \n New line (Line break) \b Backspace \t Horizontal Tab \f Form feed \a Alert (alerts a bell) \r Carriage Return \v Vertical Tab \? Question Mark \' Single Quote \'' Double Quote \\ Backslash \0 Null Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

13 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Constants A constant is an entity that doesn't change during the execution of a program. Types of constants in ‘C’  REAL CONSTANT It must have at least one digit. It must have a decimal point which may be positive or negative. Use of blank space and comma is not allowed between real constants. Example: , Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

14 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
 INTEGER CONSTANT It must have at least one digit. It should not contain a decimal place. It can be positive or negative. Use of blank space and comma is not allowed between real constants. Example: 1990, 194, -394 CHARACTER CONSTANT t is a single alphabet or a digit or a special symbol enclosed in a single quote. Maximum length of a character constant is 1. 'T', '9', '$' Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

15 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
STRING CONSTANT It is collection of characters enclosed in double quotes. It may contain letters, digits, special characters and blank space. Example: “Hello how r u?” Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

16 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Data Types in ‘C’ Data type can be defined as the type of data of variable or constant which it stores. Data types are broadly classified as: Basic data types (primitive /fundamental data types) Derived data types User-defined data types Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

17 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Basic/Primitive Data Types The five basic data types and their corresponding keywords are: Character (char) Integer (int) Single-precision floating point (float) Double-precision floating point (double) No value available (void) Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

18 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Derived Data Types Array type e.g. char a[]; int c[] Pointer type e.g. char *, int *, float * Function type e.g int f(int, int), float f1(int) Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

19 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
User-defined Data Types Structure Union enumeration Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

20 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Type qualifiers and Type Modifiers Type Qualifiers A type qualifier neither affects the range of values nor the arithmetic properties of the declared object. const: Declaring an object const announces that its value will not be changed during the execution of a program. Volatile : The volatile type qualifier declares an item whose value can legitimately be changed by something beyond the control of the program in which it appears, such as a concurrently executing thread. Type Modifiers Signed (signed) Unsigned (unsigned) Short (short) Long (long) Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

21 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Data types size and range Type Size (Bytes) Range Format Representation char or signed char 1 -128 to 127 %c 2’s complement ASCII unsigned char 0 to 255 Binary ASCII int or signed int 2 -32,768 to 32,767 %d 2’s complement unsigned int 0 to 65535 %u Binary short int or signed short int unsigned short int long int or signed long int 4 -2,147,483,648 to 2,147,483,647 %ld unsigned long int 0 to 4,294,957,295 %lu float 3.4E-38 to 3.4E+38 %f IEEE double 8 1.7E-308 to 1.7E+308 %lf long double 10 1.7E-4932 to 1.7E+4932 %Lf Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

22 Storage Classes Automatic Register Static External Storage Memory
CPU registers Default initial value Garbage value Scope Local to the block or function Global Life Till control is in the block Persists between different function calls Till program is in execution Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

23 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Structure of C Program Documentation Section Link Section Definition Section Global Declaration Section Main() Function Section { } Subprogram Section Function1 Function2 function3 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

24 Comments Statements in ‘C’
Comments are used to convey a message and to increase the readability of a program. They are not processed by the compiler. Single line comment It starts with // and ends with the end of line Multi-line comment /* statements*/ Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

25 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Operators in ‘C’ An operator specifies the operation to be applied to its operands. Classification of Operators The operators are classified on the basis of the following criteria The number of operands on which an operator operates The role of an operator. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

26 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Classification based on number of operands Unary operators E.g. &, sizeof, !, ~, ++, -- , etc. Binary operators E.g. +, -, *, %, /, &&, &,|, etc. Ternary operator It operates on three operands. Conditional operator is the only ternary operator. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

27 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Classification Based on Role of Operator Arithmetic operators Relational operators Logical operators Bitwise operators Assignment operators Miscellaneous operators Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

28 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Arithmetic operators Operators Description Associativity * Multiplication Left to right / Division % Remainder + Addition - Subtraction Unary Operators Plus Right to left minus Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

29 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Relational operators Operators Description Associativity < Less than Left to Right <= Less than equal to > Greater than >= Greater than or equal to == Equal to != Not equal to Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

30 Logical operators Assignment Operator Operators Description
Associativity && AND Left to Right || OR ! NOT Right to left Operators Description Associativity = Assignment operators Right to left *= /= += -= %= &=,|=, ^= ,<<=, >>= Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

31 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Increment and Decrement Operators Conditional Operators Type cast operator Operators Description Associativity ++ Increment Right to Left -- Decrement Operators Description Associativity ?: Conditional or Ternary Operator Right to Left Operators Description Associativity (type) Type cast Right to Left Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

32 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Bitwise Operators Special Operators Operator Description Associativity & Bitwise AND Left to right | Bitwise OR ^ Bitwise XOR << Left shift >> Right shift ~ Bitwise Not (1’s complement) Right to left Operator Description Associativity sizeof Size of a data type Right to Left , Comma Left to Right () Function call Left to right [] Array subscript Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

33 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Precedence of Operators Rank (#) Category Operator 1 Highest () 3 multiplicative * [] / 2 Unary + % - 4 Additive ++ -- 5 Shift << ! >> ~ 6 Relational < <= & > sizeof >= (type) 7 equality ==, != Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

34 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Precedence of Operators Rank (#) Category Operator 1 Highest () 3 multiplicative * [] / 2 Unary + % - 4 Additive ++ -- 5 Shift << ! >> ~ 6 Relational < <= & > sizeof >= (type) 7 equality ==, != Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

35 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Precedence of Operators cont.… Rank (#) Category Operator 8 Bitwise & ^= ^ |= | <<= 9 Logical && >>= || 12 comma , 10 Conditional ?: 11 Assignment = *= /= %= += -= &= Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

36 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Type conversions in expressions Implicit conversions Char/short int unsigned int long int unsigned long int float double long double Conversion Hierarchy Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

37 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Explicit Conversion Syntax (type) expression Example X= (int) 100.9 Z= (int) 23.6*(int)34.5 K=(double) (a+b-c) N=sin((float)v) Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

38 1.9 Decision Statements in ‘C’
The if statement The if-else statement The conditional operators Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

39 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
If statement If( condition) statement1; e.g. If (2<3) printf(“I won”); start a=10 b=10 a<b Display “Hello” stop Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

40 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Multiple statements in if If( condition) { Statement1; Statement2; Statement3; } The if-else statement If( condition ) else Entry False True Expression Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

41 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
if Statement if (booleanExpression) { statement1; statement2; statementn; } If you have multiple subordinate statements, these must be a block enclosed in braces. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

42 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
if flowchart Boolean test Subordinate statement(s) Independent statement(s) true false Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

43 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
If – else with multiple statements if(condition) { Statement1; Statement2; Staement3; } else Statement3; Nested if- elses if(condn) { do this; } else if() Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

44 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
The else if clause if(condition1) do this else if(condition2) else if(condition3) do this; else Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

45 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Nested if Statements This is true indentation for the nesting… inner ifs are nested within else of previous if statement. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

46 FlowChart for if – else if -- else
Boolean test statement(s) subordinate to if Independent statement(s) true false statement(s) subordinate to elseif statement(s) subordinate to else Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

47 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Conditional Operator ?: expression1 ? Expression1 : expression 2 Example X= a<b? a:b Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

48 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
switch…..case statement in ‘C’ switch(expression) { case value-1: block-1; break; case value-2: block-2: ……….. ………… default: default-block } statement-x; Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

49 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Write switch case from the flow-chart Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

50 Control/Loop Statements
while loop do…while loop for loop Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

51 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
While loop while (test condition) { body of the loop } Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

52 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Example for while loop int i = 0; while (i < 10) { printf("Welcome to C!"); i++; } Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

53 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
do… while do { body of the loop }while( test-condition ); Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

54 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
statement_before; while (condition) { statement_inside1; statement_inside2; ... } statement_after; Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

55 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
for loop for (initialization ; test-condition ; increment) { body of the loop } Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

56 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
for (counter = initial_value; counter <= final value; counter++) { statement1; statement2; ... } /* for counter */ statement_after; Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

57 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Example for loop #include <stdio.h> void main() { // using for loop statement int max = 5; int i = 0; for(i = 0; i < max;i++) printf("%d\n",i); } Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

58 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Break statement… It is used to exit from a loop or a switch, control passing to the first statement beyond the loop or a switch. With loops, break can be used to force an early exit from the loop, or to implement a loop with a test to exit in the middle of the loop body A break within a loop should always be protected within an if statement which provides the test to control the exit condition. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

59 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Continue …. statement This is similar to break but is encountered less frequently. It only works within loops where its effect is to force an immediate jump to the loop control statement. In a while loop, jump to the test statement. In a do while loop, jump to the test statement. In a for loop, jump to the test, and perform the iteration. Like a break, continue should be protected by an if statement. You are unlikely to use it very often. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

60 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
goto statement The goto statement transfers program execution to some label within the program. The goto is a unconditional branching statement used to transfer control of the program from one statement to another. Syntax: goto label; .... label: Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

61 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
it is a good practice to avoid using goto. In case any goto is absolutely necessary, it should be documented. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

62 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Jumping out of the program We can jump out of a program using exit() function. It takes an integer as its argument. Normally 0 is used to indicate normal termination and non-zero value to indicate termination due to some error or abnormal condition. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

63 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Functions in ‘C’ A function in C language is a block of code that performs a specific task. A function is a sub-unit of a program which performs a specific task. There are two types of functions in ‘C’ Library functions User defined functions C has a rich set of library functions. Some of them are scanf(), printf(), sqrt(), con(), sin() etc. User defined functions are written at the time of program development Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

64 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Advantages of User-defined functions A large program is difficult to test, debug and update. A large program can be divided into functions and each function can be written independently A program written as a single main() function is difficult to write as it becomes too large to handle. A number of people can work together on a program. every person can be assigned a task of developing some function. Function improve readability of a program. The length of source program can be reduced by using functions. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

65 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Structure of a Function A general form of a C function looks like this: <return type> FunctionName (Argument1, Argument2, Argument3……) { Statement1; Statement2; Statement3; } An example of function. int sum (int x, int y) { int result; result = x + y; return (result); } Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

66 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
5/17/2019

67 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
The form of a C function Function name The number and kind o arguments The return type of the function. Declaring functions using prototypes Passing arguments to function Returning values from functions Scope of a functions Inline functions Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

68 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Inline Functions Inline are actually Macros but are written like a function. Normal functions need to be called and involves passing of parameter but inline functions has no such overhead calling. When we use an inline function the compiler puts the entire code for the function directly into the code when the function is called. To create inline function we use keyword inline Inline functions are called like the normal functions. Ex. inline float area(float height, float base ) Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

69 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
MACROS Macros are declared in C using the preprocessor directive ‘# define’ Syn #define name replacement string Ex. #include<stdio.h> #define MAX // during preprocessing Void main() // the preprocessor replaces { // MAX by 10 int i; for( i=0; i< MAX; i++) printf(“\n hello”); } Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

70 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
MACROS with arguments Ex. #include<stdio.h> #define AREA(x) (x*x*3.14) //(10*10*3.14) Main() { is passed as argument float a, r = 10; a = AREA( r ); printf(“ Area of circle is:”,a); } Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

71 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Macro Expansion # define A //declaration During preprocessing, the preprocessor replaces every occurrence of A in the program with 100. Use capital letters for macro template. A macro definition is never terminated by semicolon. A #define directive is many a times used to define operators as shown below. #define AND && #define OR || Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

72 MACRO, FUNCTION Comparison
Both Macro and Function make a program more readable. If a part of code is repeated very often then it is written as Macro or Function. Every call of Macro is physically replaced by its body, thus increases the code size. When a Function is called the control is passed to the called function and returns back to the calling function after execution of the function. Small task should be written as Macro whereas large and complex task should be written as Function to save memory. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

73 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Calling a macro and a function In a macro call, the preprocessor replaces the macro template with its macro expansion. In a function, the control is passed to a function along with certain arguments. Execution time and Memory Usually macros make the program run faster but increases the program size . Functions make the program smaller and compact, but executes slowly. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

74 Arrays and String manipulation
Introduction Defn : An array is a collection of similar elements. An array is a collective name given to a group of similar quantities. Array elements begins with 0. To access an individual data item, you need to indicate to the computer which array element you want. This is done by specifying the array index or the subscript in brackets after the array name. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

75 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
A Simple Program Using Array: Let us try to write a program to find average marks obtained by a class of 30 students in a test. main( ) { int avg, sum = 0 ; int i ; int marks[30] ; /* array declaration */ for ( i = 0 ; i <= 29 ; i++ ) printf ( "\nEnter marks " ) ; scanf ( "%d", &marks[i] ) ; /* store data in array */ } sum = sum + marks[i] ; /* read data from an array*/ avg = sum / 30 ; printf ( "\nAverage marks = %d", avg ) ; Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

76 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Ordinary variables are capable of holding only one value at a time. However, there are situations in which we would want to store more than one value at a time in a single variable. In such a case we have two options to store these marks in memory: a).Construct 100 variables to store percentage marks obtained by 100 different students, i.e. each variable containing one student’s marks. b).Construct one variable (called array or subscripted variable) capable of storing or holding all the hundred values. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

77 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Representation and Analysis Arrays must be declared before they are used. The general form of array declaration is: type variable_name[size] The type specifies the type of the element to be stored in the array . Type could be any of the primitive types like int, float, char, long, double, etc. or user defined type. For example: int number[10]; Declares an array of 10 integer constant with the name number. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

78 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
It may be noted that strings are stored in character array and a string is terminated by a null character (‘\0’). “CLASS” Each character of the string is treated as an array element and is stored in the memory as given below : Name[0] Name[1] ‘C’ ‘L’ ‘A’ ‘S’ ‘\0’ Name[i] represents individual element of the string, where as name without any subscript indicates the entire string. Name[2] Name[3] Name[4] Name[5] Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

79 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Accessing Elements of an Array: This is done with subscript, the number in the brackets following the array name. This number specifies the element’s position in the array. All the array elements are numbered, starting with 0. For example: marks[2] is not the second element of the array, but the third. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

80 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Entering Data into an Array Section of a program to enter data in the array: for ( i = 0 ; i <30 ; i++ ) { printf ( "\n Enter marks " ) ; scanf ( "%d", &marks[i] ) ; } The for loop causes the process of asking for and receiving a student’s marks from the user to be repeated 30 times. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

81 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Reading Data from an Array: The for loop is much the same, but now the body of the loop causes each student’s marks to be added to a running total stored in a variable called sum. When all the marks have been added up, the result is divided by 30, the number of students, to get the average. for ( i = 0 ; i <= 29 ; i++ ) sum = sum + marks[i] ; avg = sum / 30 ; printf ( "\n Average marks = %d", avg ) ; Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

82 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Array Initialisation: Let us now see how to initialize an array while declaring it. Following are a few examples that demonstrate this. 1). int num[6] = { 2, 4, 12, 5, 45, 5 } ; 2). int n[ ] = { 2, 4, 12, 5, 45, 5 } ; 3). float press[ ] = { 12.3, , } ; Note the following points carefully: Till the array elements are not given any specific values, they are supposed to contain garbage values. If the array is initialised where it is declared, mentioning the dimension of the array is optional as in the 2nd example above. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

83 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Array Elements in Memory : Consider the following array declaration: int arr[8] ; What happens in memory when we make this declaration? 16 bytes get immediately reserved in memory, 2 bytes each for the 8 integers. Whatever be the initial values, all the array elements would always be present in contiguous memory locations. This arrangement of array elements in memory is shown in the following figure: 12 34 51 23 -19 66508 66510 66512 66514 66516 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

84 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Few important points that should be kept in mind while using arrays: An array is a collection of homogeneous(similar) elements. The first element in the array is numbered 0, so the last element is 1 less than the size of the array. An array is also known as a subscripted variable. Before using an array its type and dimension must be declared. However big an array its elements are always stored in contiguous memory locations. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

85 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Few important points that should be kept in mind while using arrays: An array is a collection of homogeneous(similar) elements. The first element in the array is numbered 0, so the last element is 1 less than the size of the array. An array is also known as a subscripted variable. Before using an array its type and dimension must be declared. However big an array its elements are always stored in contiguous memory locations. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

86 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
STRINGS Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

87 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
String A set of characters is known as a string.  char st[80];  st array with 80 characters. \0  A ‘null character’ is placed automatically at the end of any string String handling functions in C- 4 important string handling functions -            strlen() function            strcpy() function            strcat() function            strcmp() function The header file #include <string.h> is used for these functions Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

88 Storing data into strings
Use scanf() function to take from user example                 scanf(“%s“, city); enter the city name (e.g. “NEWDELHI”) without any white space i.e. not like “NEW DELHI” The white space will terminate the reading and only “NEW” is assigned to city. To read a string with white spaces gets() function or a loop can be used as follows:            gets(city); We can enter “new delhi” also. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

89 Storing data into strings
By using loop- take from user char name[10]; for(i=0; i<10 ;i++) { scanf(“%c”,&name[i]); } Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

90 Reading data from strings
Use printf() function to read string example char city[10];                 printf(“%s“, city); To print a string on screen             puts(city); By using loop- char city[10]; for(i=0; i<10 ;i++) { printf(“%c”, city[i]); } Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

91 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
strlen() function used to find the length of a character string. example.           int n;           char st[20] = “Bangalore”;           n = strlen(st); This will return the length of the string 9 which is assigned to an integer variable n. Note that the null character ‘\0’ available at the end of a string is not counted. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

92 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
strcpy() function Used to copy a character string to another character string. Syntax-   strcpy(destination, source); example.            char city[15];            strcpy(city, “ BANGALORE “); This will assign the string “BANGALORE” to the character variable city. example.            char city[15]=“pune”; char name[10]=“nasik”;            strcpy(city , name); City=nasikafter strcpy. It will overwrite the previous contents of the array. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

93 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
strcat() Function Used to join character strings or append string.  When two character strings are joined, it is referred as concatenation of strings. Syntax- strcat(destination, source); example.        char city[20] = “BANGALORE“;        char pin[8] = “pune“;        strcat( city, pin); It will apend or join the two strings and store the result in city as   city=  “Bangalorepune”.` Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

94 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
strcmp() function used to compare two character strings. It returns -  when two strings are identical; <0 or >0  when two strings are not identical; It will find the the difference in ASCII values of the first mismatching characters of the strings being compared. example. int n;           char city[20] = “MADRAS”;           char town[20] = “MANGALORE”;           n=strcmp(city, town); if(n==0) printf(“both strings are equal”); else printf(“both strings are not equal”); It will return value  10 which is the difference in the ASCII values of the first mismatching letters ‘D’ and ‘N’.          Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

95 Structure union enumerated data types
STRCUTURES Structure union enumerated data types

96 Structure of a Structure
STRCUTURES Structure of a Structure A structure contains a number of data types grouped together. These data types may or may not be of the same type. A structure gathers together, different atoms of information that comprise a given entity. There are two fundamental aspects of structures: (a) Declaration of a structure (b) Accessing of structure elements The general form of a structure declaration statement is given below: struct <structure name> { structure element 1 ; structure element 2 ; ...... } ; Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

97 Structure of a Structure(contd)
STRCUTURES Structure of a Structure(contd) The following statement declares the structure type: struct book { char name ; float price ; int pages ; } ; This statement defines a new data type called struct book. Each variable of this data type will consist of a character variable called name, a float variable called price and an integer variable called pages. Once the new structure data type has been defined one or more variables can be declared to be of that type. For example the variables b1, b2, b3 can be declared to be of the type struct book, as, struct book b1, b2, b3 ; This statement sets aside space in memory. It makes available space to hold all the elements in the structure—in this case, 7 bytes—one for name, four for price and two for pages. These bytes are always in adjacent memory locations. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

98 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
STRCUTURES Array of Structures /* Usage of an array of structures */ main( ) { struct book char name ; float price ; int pages ; } ; struct book b[100] ; // An Array of size 100 of structure type declared and memory allocated to it. int i ; for ( i = 0 ; i <= 99 ; i++ ) printf ( "\nEnter name, price and pages " ) ; scanf ( "%c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ; } printf ( "\n%c %f %d", b[i].name, b[i].price, b[i].pages ) ; linkfloat( ) // CONCEPT NOT INCLUDED IN SYLLABUS float a = 0, *b ; b = &a ; /* cause emulator to be linked */ a = *b ; /* suppress the warning - variable not used */ No need to call link float. Jst define it ne wer in d prog Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

99 Array of Structures(contd..)
Notice how the array of structures is declared... struct book b[100] ; This provides space in memory for 100 structures of the type struct book. The syntax we use to reference each element of the array b is similar to the syntax used for arrays of ints and chars. For example, we refer to zeroth book’s price as b[0].price. Similarly, we refer first book’s pages as b[1].pages. In an array of structures all elements of the array are stored in adjacent memory locations. Since each element of this array is a structure, and since all structure elements are always stored in adjacent locations . We can very well visualize the arrangement of array of structures in memory. In our example, b[0]’s name, price and pages in memory would be immediately followed by b[1]’s name, price and pages, and so on. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

100 The Inside Story(Storage)
Elements of a Structure are always stored in contiguous memory locations. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

101 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Miscellaneous 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. ACESS: In Structures, we can access individual elements of a structure using a dot (.) operator. So to refer to pages of the structure defined in our sample program we have to use, b1.pages Note: Before the dot there must always be a structure variable and after the dot there must always be a structure element. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

102 Additional Features of Structures
STRCUTURES Additional Features of Structures One structure can be nested within another structure main( ) { struct address char phone[15] ; char city[25] ; int pin ; } ; struct emp char name[25] ; struct address a ; struct emp e = { "jeru", "531046", "nagpur", 10 }; printf ( "\nname = %s phone = %s", e.name, e.a.phone ) ; printf ( "\ncity = %s pin = %d", e.a.city, e.a.pin ) ; } Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

103 Additional Features of Structures(contd..)
And here is the output... name = jeru phone = city = nagpur pin = 10 Notice the method used to access the element of a structure that is part of another structure. For this the dot operator is used twice, as in the expression, e.a.pin or e.a.city Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

104 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Uses of Structures Database Management is obviously one of its numerous application. That is, to maintain data about employees in an organization, books in a library, items in a store, financial accounting transactions in a company etc. To List others are: Changing the size of the cursor Clearing the contents of the screen Placing the cursor at an appropriate position on screen Drawing any graphics shape on the screen Receiving a key from the keyboard Checking the memory size of the computer Finding out the list of equipment attached to the computer Formatting a floppy Hiding a file from the directory Displaying the directory of a disk Sending the output to printer Interacting with the mouse Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

105 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Enumerated Data Types The Enumerated data type gives us an opportunity to invent our own data types and define what values the variable of this data type can take. This can help in making the program listings more readable, which can be advantage when a program gets complicated or in situations when more than one users would be working on it. The format of the enum definition is similar to that of a structure. Lets have an example to illustrate it: enum mar_status { single, married, divorced, widowed }; Enum mar_status person1,person2; The above declaration has two parts(like in structure): (a)The first part declares the data type and specifies its possible values These values are called ‘Enumerators’. (b)The second part declares variables of this data type. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

106 Enumerated Data Types(contd..)
Now we an give values to these variables as person1=married; person2=divorced; NOTE: We cant use values that are not in the original declaration. e.g.preson1=unknown; is an invalid statement . Internally, the compiler treats the enumerators as integers. Each value on the list of permissible value corresponds to an integer, starting with 0. Thus married will be stored as 1 and so on. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

107 Use of Enumerated Data Types
They are generally used to clarify the operation of a program. It makes listing easier to read if we use values like Assembly, Manufacturing or accounts rather than 0,1,2,etc. Note: The same effect- readability and convenience can be achieved using MACROS. Then why enums ??? Coz macros have a global scope, whereas scope of enums can be global or local depending on location of declaration. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

108 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Union They are another type of derived data types. Let us have a simple example: /*Demo of union at work*/ #include<stdio.h> void main() { union a int I; char ch[2]; }; union a key; key.i=512; printf(“\nkey.i=%d”,key.i); printf(“\nkey.ch[0]=%d”,key.ch[0]); printf(“\nkey.ch[1]=%d”,key.ch[1]); } Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

109 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Union(contd..) And the o/p is key.i=512 key.ch[0]=0 key.ch[1]=1 . Unions and structures look alike but are engaged in totally different enterprises. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

110 Difference b/w Structure And Union
The most crucial difference is that of memory allocation which is described as follows: For a structure variable the memory allocation would be as follows and would occupy 4 bytes of memory. While for a union declaration the memory allocation would be as follows: As shown union occupies only 2 bytes of memory. Here same memory locations are used for storage of different variables. The other implied difference is that structure allows access of two structure elements simultaneously while union prohibits the simultaneous access. key.i key.ch[0] key.ch[1] key.i key.ch[0] key.ch[1] Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

111 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
Utility of Unions Unions provides a useful solution where problems of space allocation arise. Also they provide access to same memory element in different ways. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019

112 Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale
References Yashwant Kanetkar, “Let Us C”, BPB Publications,8th Edition. Herbert Schildt, “The Complete Reference”, Tata McGraw-Hill, 4th Edition. E. Balagurusamy, “Programming In ANSI C”, McGraw-Hill Companies, 4th edition. Dennis M. Ritchie,and Brian W. Kernighan, “The C Programming Language”,PHI, 2nd Edition Ajay Mittal, “Programming in C A Practical Approach”, Pearson. Dept. of Comp. Engg. BSCOER, Narhe Prof. N. B. Pokale 5/17/2019


Download ppt "Unit-III C Programming"

Similar presentations


Ads by Google