Download ppt - Programming in c

Transcript
Page 1: Programming in c

PROGRAMMING IN C

UNIT- I

Fundamental of Computer programming -206

Page 2: Programming in c

By- Er. Indrajeet Sinha , +919509010997

UNIT-1 1.1- Representing Algorithms through flowchart, pseudo code

. 1.2- Concept of Programming Languages and Language transl

ator. 1.3- Introduction to Programming and structure of C Program. 1.4- Identifiers, Constants, Variables. 1.5- Basic Data Types. 1.6- Operators, Expressions in C, type casting. 1.7- Input Statement. 1.8- Output Statement. 1.9- Scope Rules and Storage classes. 1.10- Concept of Preprocessor and Macro Substitution.

2

Page 3: Programming in c

REPERSENTING ALGORITHMS THROUGH FLOWCHARTS & PSEUDO CODE

Lecture no.- 1, UNIT- I

Page 4: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.1- INTRODUCTION Definition:-

What is Program? A computer program is a collection of instructions that

performs a specific task when executed by a computer. A computer requires programs to function, and typically executes the program's instructions in a central processing unit.

What is programming language? A programming language is a formal computer language

designed to communicate instruction to a machine, particularly a computer. Programming language can be used to create programs to control the behavior of a machine or to express algorithms.

Page 5: Programming in c

By- Er. Indrajeet Sinha , +919509010997

DEFINITION’S What is an algorithm? A process or set of rules to be followed in

calculations or other problem-solving operations, especially by a computer.

What is Flow Chart ? Pictorial representation of an algorithm is known

as flow chart, it use some special symbol to represent instruction set.

What is Pseudocode?

Artificial, informal language used to develop algorithms Similar to everyday English

Page 6: Programming in c

By- Er. Indrajeet Sinha , +919509010997

WHY ALGORITHMS & FLOWCHARTS ?

A typical programming task can be divided into two phases:

Problem solving phase produce an ordered sequence of steps that

describe solution of problem this sequence of steps is called an algorithm

Implementation phase implement the program in some programming

language

Page 7: Programming in c

By- Er. Indrajeet Sinha , +919509010997

STEPS IN PROBLEM SOLVING

First produce a general algorithm (one can use pseudocode)

Refine the algorithm successively to get step by step detailed algorithm that is very close to a computer language.

Pseudocode is an artificial and informal language that helps programmers develop algorithms. Pseudocode is very similar to everyday English.

Page 8: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.1.1- THE FLOWCHART

A graphical representation of the sequence of operations in an information system or program. Information system flowcharts show how data flows from source documents through the computer to final distribution to users. Different symbols are used to draw each type of flowchart.

Page 9: Programming in c

By- Er. Indrajeet Sinha , +919509010997

FLOWCHART SYMBOLS

Oval

Parallelogram

Rectangle

Diamond

Hybrid

Name Symbol Use in Flowchart

Denotes the beginning or end of the program

Denotes an input operation

Denotes an output operation

Denotes a decision (or branch) to be made. The program should continue along one of two routes. (e.g. IF/THEN/ELSE)

Denotes a process to be carried oute.g. addition, subtraction, division etc.

Flow line Denotes the direction of logic flow in the program

Page 10: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.1.1.1- SEQUENTIAL FLOW CHART

Page 11: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.1.1.2- CONDITIONAL FLOW CHART

Page 12: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.1.1.3 LOOPING FLOW CHART

Page 13: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.1.2 PSEUDO CODE Definition:-

Pseudo code is a simple way of writing programming code in English.

Pseudo code (pronounced SOO-doh-kohd) is a detailed yet readable description of what a computer program or algorithm must do, expressed in a formally-styled natural language rather than in a programming language.

Pseudocode is an artificial and informal language that helps programmers to develop algorithms.

Page 14: Programming in c

By- Er. Indrajeet Sinha , +919509010997

PSEUDOCODE & ALGORITHM

Example 1: Write an algorithm to determine a student’s final grade and indicate whether it is passing or failing. The final grade is calculated as the average of four marks.

Page 15: Programming in c

By- Er. Indrajeet Sinha , +919509010997

PSEUDOCODE & ALGORITHM

Pseudocode: Input a set of 4 marks Calculate their average by summing

and dividing by 4 if average is below 50

Print “FAIL”else

Print “PASS”

Page 16: Programming in c

By- Er. Indrajeet Sinha , +919509010997

EXAMPLE

PRINT“PASS”

Step 1: Input M1,M2,M3,M4Step 2: GRADE (M1+M2+M3+M4)/4 Step 3: if (GRADE <50) then

Print “FAIL” else

Print “PASS” endif

START

InputM1,M2,M3,

M4

GRADE(M1+M2+M3+M4)/4

ISGRADE<

50

PRINT“FAIL”

STOP

YN

Page 17: Programming in c

By- Er. Indrajeet Sinha , +919509010997

EXAMPLE 2

Write an algorithm and draw a flowchart to convert the length in feet to centimeter.

Pseudocode: Input the length in feet (Lft) Calculate the length in cm (Lcm) by

multiplying LFT with 30 Print length in cm (LCM)

Page 18: Programming in c

By- Er. Indrajeet Sinha , +919509010997

EXAMPLE 2

Algorithm Step 1: Input Lft Step 2: Lcm Lft x 30 Step 3: Print Lcm

START

InputLft

Lcm Lft x 30

PrintLcm

STOP

Flowchart

Page 19: Programming in c

By- Er. Indrajeet Sinha , +919509010997

CONCLUSION OF LECTURE-1

In this lecture we knew about program, algorithm and pseudo code.

We also knew about different type of flow chart.

We also exercise on different types of example for create flow chart and pseudo code.

19

Page 20: Programming in c

CONCEPT OF PROGRAMMING LANGUAGES AND LANGUAGE TRANSLATORS

Lecture no. -2, UNIT- I

Page 21: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.2.1 LOW LEVEL LANGUAGE

Definition:- In computer science, a low-

level programming language is a programming language that provides little or no abstraction from a computer's instruction set architecture—commands or functions in the language map closely to processor instructions. Generally this refers to either machine code or assembly language.

Low-level language is a programming language that deals with a computer's hardware components and constraints. ... 

Low-level language may also be referred to as a computer’s native language. ...

Machine language and assembly language are popular examples of low level languages.

Page 22: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.2.2 HIGH LEVEL LANGUAGE

Definition:

A high-level language is a programming language such as C, FORTRAN, or Pascal that enables a programmer to write programs that are more or less independent of a particular type of computer. Such languages are considered high-level because they are closer to human languages and further from machine languages.

High-level language is any programming language that enables development of a program in much simpler programming ...

Page 23: Programming in c

By- Er. Indrajeet Sinha , +919509010997

ASSEMBLY LANGUAGE

Definition: A low level language that is similar to machine

language.

Uses symbolic operation code to represent the machine operation code.

Page 24: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.2.3 LANGUAGE TRANSLATOR

Definition: A translator is a computer program that performs

the translation of a program written in a given programming language into a functionally equivalent program in a different computer language, without losing the functional or logical structure of the original code (the "essence" of each program).

Programming language processor (assembler, compiler, or interpreter) that converts a computer program written in one language to another language.

Page 25: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.2.3.1 ASSEMBLER Definition:

An assembler is a program that takes basic computer instructions and converts them into a pattern of bits that the computer's processor can use to perform its basic operations.

Assembler may refer to: Assembler (computing), a computer program which translates assembly language to an object file or machine language format.

Software that translates assembly language into machine language.

Assembler

Assembly language code

Object code

Page 26: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.2.3.2 INTERPRETER Definition:

Computer language processor that translates a program line-by-line (statement-by-statement) and carries out the specified actions.

An interpreter translates high-level instructions into an intermediate form, which it then executes. In contrast, a compiler translates high-level instructions directly into machine language.

Page 27: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.2.3.3 COMPILER Definition:

A compiler is a special program that processes statements written in a particular programming language and turns them into machine language or "code" that a computer's processor uses. Typically, a programmer writes language statements in a language such as Pascal or C one line a

A compiler is a computer program (or a set of programs) that transforms source code written in a programming language (the source language) into another computer language (the target language), with the latter often having a binary form known as object code.

Page 28: Programming in c

By- Er. Indrajeet Sinha , +919509010997

SOFTWARE LANGUAGE LEVELS

Machine Language (Binary) Assembly Language

Assembler converts Assembly into machine High Level Languages (C, Perl, Shell)

Compiled : C Interpreted : Perl, Shell

Page 29: Programming in c

By- Er. Indrajeet Sinha , +919509010997

SOME TERMS

Source The language program was written in

Object The machine language equivalent of the program after

compilation Compiler

A software program that translates the source code into object code

Assembler is a special case of compiler where the source was written in Assembly language

Page 30: Programming in c

By- Er. Indrajeet Sinha , +919509010997

CONVERT SOURCE TO OBJECT Example:

SUM = A + BCompiles to Machine language of:

LDR R1, ALDR R2, BADD R1, R1, R2STR R1, C

Page 31: Programming in c

By- Er. Indrajeet Sinha , +919509010997

STEPS FOR COMPILATION

Create/Edit source Compile source Link object modules together Test executable If errors, Start over Stop

Page 32: Programming in c

By- Er. Indrajeet Sinha , +919509010997

COMPILATION PROCESS: Invoke compiler on source program to generate

Machine language equivalent Compiler translates source to object Saves object output as disk file[s] Large Systems may have many source programs Each has to be compiled

Page 33: Programming in c

By- Er. Indrajeet Sinha , +919509010997

INTERPRETATION

No linking No object code generated Source statements executed line by line

Page 34: Programming in c

By- Er. Indrajeet Sinha , +919509010997

STEPS IN INTERPRETATION

Read a source line Parse line Do what the line says

Allocate space for variables Execute arithmetic opts etc.. Go to back to step 1

Similar to instruction cycle

Page 35: Programming in c

By- Er. Indrajeet Sinha , +919509010997

INTERPRETER ADVANTAGES

Easier to debug Faster development time

Some Interpretive Systems Languages

BASIC, Perl, Lisp

OS Interfaces C Shell, Bourne Shell WINEXEC

Page 36: Programming in c

INTRODUCTION TO PROGRAMMING AND STRUCTURE OF C PROGRAM

Lecture no. -3, UNIT- I

Page 37: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.3.1 NEED OF PROGRAMMING LANGUAGES

A programming language is a formal computer Language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs to control the behavior of a machine or to express algorithms.

For make easy work.

Page 38: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.3.2 INTRODUCTION AND FEATURES OF C

C is a high-level and general

purpose programming language that is ideal for developing firmware or portable applications.

C is a structured, procedural programming language that has

been widely used both for operating systems

and applications

C is a high-level programming

language developed by Dennis Ritchie at Bell Labs in the mid 1970s.

Although originally designed as a System 

programming language.

C has proved to be a powerful and flexible language that can

be used for a variety of applications, from business programs to engineering.

Page 39: Programming in c

By- Er. Indrajeet Sinha , +919509010997

C - HISTORY

Developed between 1969 and 1973 along with Unix

Due mostly to Dennis Ritchie Designed for systems programming

Operating systems Utility programs Compilers Filters

Evolved from B, which evolved from BCPL Designed by Martin Richards (Cambridge) in 1967 Type less

Everything an n-bit integer (a machine word) Pointers (addresses) and integers identical

Memory is an undifferentiated array of words

Page 40: Programming in c

By- Er. Indrajeet Sinha , +919509010997

FEATURES OF C

Page 41: Programming in c

By- Er. Indrajeet Sinha , +919509010997

CONT…

Low Level Features : C Programming provides low level features that are

generally provided by the Lower level languages. C is Closely Related to Lower level Language such as “Assembly Language“.

It is easier to write assembly language codes in C programming.

  Portability :

C Programs are portable i.e they can be run on any Compiler with Little or no Modification

Compiler and Preprocessor make it Possible for C Program to run it on Different PC

Page 42: Programming in c

By- Er. Indrajeet Sinha , +919509010997

 Powerful: Provides Wide verity of ‘Data Types‘ Provides Wide verity of ‘Functions’ Provides useful Control & Loop Control Statements

Bit Manipulation: C Programs can be manipulated using bits. We can

perform different operations at bit level. We can manage memry representation at bit level. [Eg. We can use Structure to manage Memory at Bit Level]

It provides wide verity of bit manipulation Operators. We have bitwise operators to manage Data at bit level.

Page 43: Programming in c

By- Er. Indrajeet Sinha , +919509010997

High Level Features : It is more User friendly as compare to Previous

languages. Previous languages such as BCPL,Pascal and other programming languages never provide such great features to manage data.

Previous languages have there pros and cons but C Programming collected all useful features of previous languages thus C become more effective language.

Modular Programming: Modular programming is a software design

technique that increases the extent to which software is composed of separate parts, called modules

C Program Consist of Different Modules that are integrated together to form complete program

Page 44: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.3.3 STRUCTURE OF A C PROGRAM

Note:-

Every C Program will have one or more functions and there is one mandatory function which is called main() function. ...

Page 45: Programming in c

By- Er. Indrajeet Sinha , +919509010997

HELLO WORLD IN C

#include <stdio.h>

void main(){ printf(“Hello, world!\n”);}

Preprocessor used to share information among source files- Clumsy+ Cheaply implemented+ Very flexible

Page 46: Programming in c

By- Er. Indrajeet Sinha , +919509010997

HELLO WORLD IN C

#include <stdio.h>

void main(){ printf(“Hello, world!\n”);}

Program mostly a collection of functions“main” function special: the entry point“void” qualifier indicates function does not return anything

I/O performed by a library function: not included in the language

Page 47: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.3.4 COMPILATION, LINKING AND EXECUTION OF A C PROGRAM

Click Here for C program Compilation Process Understanding C program Compilation Process visit,https://youtu.be/VDslRumKvRA

Page 48: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.3.5 - OBJECT CODE, INTERMEDIATE CODE, EXECUTABLE CODE

Definition:

source code: In computing, source code is any collection of computer instructions, (possibly with comments), written using a human-readable programming language, usually as ordinary text.

Page 49: Programming in c

By- Er. Indrajeet Sinha , +919509010997

Definition:Intermediate Code: A source code can directly

be translated into its target machine code, then why at all we need to translate the source code into an intermediate code which is then translated to its target code? Let us see the reasons why we need an intermediate code.

49

Page 50: Programming in c

By- Er. Indrajeet Sinha , +919509010997

Object code: It is the output of a compiler after it processes source code. 

Executable code: Software in a form that can be run in the computer. It typically refers to machine language, which is the set of native instructions the computer carries out in hardware.

50

Page 51: Programming in c

By- Er. Indrajeet Sinha , +919509010997

51

Page 52: Programming in c

IDENTIFIERS, CONSTANTS, VARIABLES,

Lecture no.- 4, UNIT- I

Page 53: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.4.1- CONSTANTS

Definition:- Constants refer to fixed values that the program

may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an Integer Constant, a floating constant, a Character Constant, or a string literal.

53

Page 54: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.4.1.1- TYPES OF CONSTANTS

54

Page 55: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.4.1.1.1 - NUMERICAL CONSTANTS

Numerical Constants Constants like 12, 253 are stored as int type. No decimal point.

12L or 12l are stored as long int. 12U or 12u are stored as unsigned int. 12UL or 12ul are stored as unsigned long int. Numbers with a decimal point (12.34) are stored as

double. Numbers with exponent (12e-3 = 12 x 10-3 ) are stored

as double. 12.34f or 1.234e1f are stored as float. These are not valid constants:25,000 7.1e 4 $200 2.3e-3.4 etc.

Page 56: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.4.1.1.2 - CHARACTER AND STRING Character and string constants

‘c’ , a single character in single quotes are stored as char.Some special character are represented as two characters in single quotes.‘\n’ = newline, ‘\t’= tab, ‘\\’ = backlash, ‘\”’ = double quotes.Char constants also can be written in terms of their ASCII code.‘\060’ = ‘0’ (Decimal code is 48).

A sequence of characters enclosed in double quotes is called a string constant or string literal. For example“Charu”“A”“3/9”“x = 5”

Page 57: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.4.1.2 - DECLARING CONSTANTS

57

Page 58: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.4.2- IDENTIFIERS, KEYWORDS

Definition: Identifiers

An Identifier is a sequence of letters and digits, but must start with a letter. Underscore ( _ ) is treated as a letter. Identifiers are case sensitive. Identifiers are used to name variables, functions etc.

Valid: Root, _getchar, __sin, x1, x2, x3, x_1, If Invalid: 324, short, price$, My Name

Keywords These are reserved words of the C language. For

example int, float, if, else, for, while etc.

58

Page 59: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.4.3- VARIABLES (VARIABLE DECLARATION RULES)

Naming a Variable Must be a valid identifier. Must not be a keyword Names are case sensitive. Variables are identified by only first 32 characters. Library commonly uses names beginning with _. Naming Styles: Uppercase style and Underscore

style lowerLimit lower_limit incomeTax income_tax

Page 60: Programming in c

By- Er. Indrajeet Sinha , +919509010997

DECLARATIONS

Declaring a Variable Each variable used must be declared. A form of a declaration statement isdata-type var1, var2,…;

Declaration announces the data type of a variable and allocates appropriate memory location. No initial value (like 0 for integers) should be assumed.

It is possible to assign an initial value to a variable in the declaration itself.data-type var = expression;

Examplesint sum = 0;char newLine = ‘\n’;float epsilon = 1.0e-6;

Page 61: Programming in c

BASIC DATA TYPES IN C

Lecture no.- 5, UNIT- I

Page 62: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.5.1- DATA TYPES

Definition Data types in c refer to an extensive

system used for declaring variables or functions of different types.

The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.

62

Page 63: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.5.1- DATA TYPES

63

Page 64: Programming in c

By- Er. Indrajeet Sinha , +919509010997

BASIC DATA TYPES CONT.. Integral Types

Integers are stored in various sizes. They can be signed or unsigned.

Example Suppose an integer is represented by a byte (8 bits). Leftmost bit is sign bit. If the sign bit is 0, the number is treated as positive. Bit pattern 01001011 = 75 (decimal). The largest positive number is 01111111 = 27 – 1 = 127. Negative numbers are stored as two’s complement or as one’s complement. -75 = 10110100 (one’s complement). -75 = 10110101 (two’s complement).

Page 65: Programming in c

By- Er. Indrajeet Sinha , +919509010997

BASIC DATA TYPES CONT..

Integral Types char Stored as 8 bits. Unsigned 0 to 255.

Signed -128 to 127. short int Stored as 16 bits. Unsigned 0 to

65535. Signed -32768 to 32767.

int Same as either short or long int. long int Stored as 32 bits. Unsigned 0

to 4294967295.Signed -2147483648 to

2147483647

Page 66: Programming in c

By- Er. Indrajeet Sinha , +919509010997

BASIC DATA TYPES CONT..

Floating Point Numbers Floating point numbers are rational numbers. Always

signed numbers. float Approximate precision of 6 decimal digits .

Typically stored in 4 bytes with 24 bits of signed mantissa and 8 bits of signed exponent.

double Approximate precision of 14 decimal digits. Typically stored in 8 bytes with 56 bits of signed mantissa and

8 bits of signed exponent.

One should check the file limits.h to what is implemented on a particular machine.

Page 67: Programming in c

By- Er. Indrajeet Sinha , +919509010997

TOKENS IN C

Keywords These are reserved words of the C language. For

example int, float, if, else, for, while etc. Identifiers

An Identifier is a sequence of letters and digits, but must start with a letter. Underscore ( _ ) is treated as a letter. Identifiers are case sensitive. Identifiers are used to name variables, functions etc.

Valid: Root, _getchar, __sin, x1, x2, x3, x_1, If

Invalid: 324, short, price$, My Name Constants

Constants like 13, ‘a’, 1.3e-5 etc.

Page 68: Programming in c

By- Er. Indrajeet Sinha , +919509010997

C- LITERALS

String Literals A sequence of characters enclosed in double quotes as

“…”. For example “13” is a string literal and not number 13. ‘a’ and “a” are different.

Operators Arithmetic operators like +, -, *, / ,% etc. Logical operators like ||, &&, ! etc. and so on.

White Spaces Spaces, new lines, tabs, comments ( A sequence of

characters enclosed in /* and */ ) etc. These are used to separate the adjacent identifiers, kewords and constants.

Page 69: Programming in c

OPERATORS, EXPRESSIONS IN C, TYPE CASTING

Lecture no.- 6, UNIT- I

Page 70: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.6.1- INTRODUCTION

Definition Operator: An operator is a symbol that tells the

compiler to perform certain mathematical or logical manipulations. Operators are used in program to manipulate data and variables. 

Expression: In programming, an exppression is any legal combination of symbols that represents a value. Each programming language and application has its own rules for what is legal and illegal. For example, in the C language x+5 is an expression, as is the character string "MONKEYS."

70

Page 71: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.6.2- TYPES OF OPERATORS BASED ON NUMBER OF OPERANDS

1.5.2.1- Unary operators:- The unary operators  operate on a single operand and

following are the examples of Unary operators. 1.5.2.2 Binary operators:-

A binary operator is an operator that operates on two operands and manipulates them to return a result. 

1.5.2.3 Ternary operators:- The ternary operator is an operator that takes three

arguments. The first argument is a comparison argument, the second is the result upon a true comparison, and the third is the result upon a false comparison. If it helps you can think of the operatoras shortened way of writing an if-else statement. 71

Page 72: Programming in c

By- Er. Indrajeet Sinha , +919509010997

UNARY OPERATORS

Operator Name Type

! Logical NOT Unary& Address-of Unary( ) Cast Operator Unary* Pointer dereference Unary+ Unary Plus Unary++ Increment Unary– Unary negation Unary–– Decrement 1 Unary~ complement Unary

72

Page 73: Programming in c

By- Er. Indrajeet Sinha , +919509010997

BINARY OPERATORS

Operator Name Type

!= Inequality Binary% Modulus Binary%= Modulus assignment Binary& Bitwise AND Binary&& Logical AND Binary

&= Bitwise AND assignment Binary

* Multiplication Binary

*= Multiplication assignment Binary

+ Addition Binary+= Addition assignment Binary– Subtraction Binary

–= Subtraction assignment Binary

–> Member selection Binary

73

Page 74: Programming in c

By- Er. Indrajeet Sinha , +919509010997

Operator Name Type

–>* Pointer-to-member selection Binary/ Division Binary/= Division assignment Binary< Less than Binary<< Left shift Binary<<= Left shift assignment Binary<= Less than or equal to Binary

74

Page 75: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.6.3- TYPES OF OPERATORS BASED ON OPERATIONS

1.6.3.1- Arithmetic Operator 1.6.3.2 - Assignment Operator 1.6.3.3 - + + and - - Operator

75

Page 76: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.6.3.1- ARITHMETIC OPERATOR

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first.

A − B = 10

∗ Multiplies both operands. A ∗ B = 200

∕ Divides numerator by de-numerator.

B ∕ A = 2

% Modulus Operator and remainder of after an integer division.

B % A = 0

++ Increment operator increases the integer value by one.

A++ = 11

-- Decrement operator decreases the integer value by one.

A-- = 9

76

Page 77: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.6.3.2 - ASSIGNMENT OPERATOR

Assignment Operator is Used to assign value to an variable.

Assignment Operator is denoted by equal to sign

Assignment Operator is binary operator which operates on two operands.

77

Page 78: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.6.3.3 - + + AND - - OPERATOR

Definition: Increment Operators are used to increased

the value of the variable by one. -Pre-Increment: ++variable -Post- increment: variable++

Decrement Operators are used to decrease the value of the variable by one. -Pre-Increment: ++variable -Post- increment: variable++

NOTE: Both increment and decrement operator are used on a single operand or variable, so it is called as a unary operator. 78

Page 79: Programming in c

By- Er. Indrajeet Sinha , +919509010997

79

Page 80: Programming in c

By- Er. Indrajeet Sinha , +919509010997

80

Page 81: Programming in c

OPERATORS, EXPRESSIONS IN C, TYPE CASTING

Lecture no.- 7, UNIT- I

Page 82: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.7.1- LOGICAL OPERATOR

Logical Operators &&, || and ! are the three logical operators. expr1 && expr2 has a value 1 if expr1 and expr2

both are nonzero. expr1 || expr2 has a value 1 if expr1 and expr2

both are nonzero. !expr1 has a value 1 if expr1 is zero else 0. Example if ( marks >= 40 && attendance >= 75 ) grade = ‘P’

If ( marks < 40 || attendance < 75 ) grade = ‘N’

Page 83: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.7.2 - TERNARY OPERATOR (CONDITIONAL OPERATOR)

Ternary operator needs exactly 3 operands to compute the result. In C, If statement can be written as ternary operator (?:).

1. if(a<b){2. c=5;3. }4. else{5. c=10;6. }

The above if block can be re-written using ternary operator like this (below).

c=(a<b)?5:10; 83

Page 84: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.7.3 - RELATIONAL OPERATORS

Relational Operators <, <=, > >=, ==, != are the relational operators.

The expressionoperand1 relational-operator operand2takes a value of 1(int) if the relationship is true and 0(int) if relationship is false.

Exampleint a = 25, b = 30, c, d;c = a < b;d = a > b;value of c will be 1 and that of d will be 0.

Page 85: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.7.4 - BITWISE OPERATOR

and: & or: | xor: ^ not: ~ left shift: << right shift: >>

Useful for bit-field manipulations

#define MASK 0x040if (a & MASK) { … } /* Check bits */c |= MASK; /* Set bits */c &= ~MASK; /* Clear bits */d = (a & MASK) >> 4; /* Select field */

Page 86: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.7.5 - OPERATOR PRECEDENCE AND ASSOCIATIVITY

Operator precedence determines which operator is performed first in an expression with more than one operators with different precedence. 

For example 10 + 20 * 30 is calculated as 10 + (20 * 30) and not as (10 + 20) * 30.

Note: Please see the following precedence and associativity table for reference.

86

Page 87: Programming in c

By- Er. Indrajeet Sinha , +919509010997

Operator Name  Associativity  Operators

Primary scope resolution

left to right ::

Primary   left to right  ()  [ ]  .  -> dynamic_cast typeid

Unary  right to left  ++  --  +  -  !  ~  &  *  (type_name)  sizeof new delete

C Pointer to Member left to right .*->*

Multiplicative  left to right  *  /  %

Additive  left to right  +  -

Bitwise Shift  left to right  <<  >>

Relational  left to right  <  >  <=  >=

Equality  left to right  ==  != 87

Page 88: Programming in c

By- Er. Indrajeet Sinha , +919509010997

CONT..

Operator Name  Associativity  Operators

Bitwise AND  left to right  &

Bitwise Exclusive OR  left to right  ^

Bitwise Inclusive OR  left to right  |

Logical AND  left to right  &&

Logical OR  left to right  ||

Conditional  right to left  ? :

Assignment  right to left  =  +=  -=  *=   /=  <<=  >>=  %=   &=  ^=  |=

Comma  left to right  ,88

Page 89: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.7.6- C EXPRESSION

arithmetic: + – * / % comparison: == != < <= > >= bitwise logical: & | ^ ~ shifting: << >> lazy logical: && || ! conditional: ? : assignment: = += -= increment/decrement: ++ -- sequencing: , pointer: * -> & []

Page 90: Programming in c

By- Er. Indrajeet Sinha , +919509010997

C EXPRESSIONS

Traditional mathematical expressions

y = a*x*x + b*x + c;

Very rich set of expressions Able to deal with arithmetic and bit

manipulation

Page 91: Programming in c

By- Er. Indrajeet Sinha , +919509010997

TERMS IN EXPRESSIONS

Evaluating an expression often has side-effects

a++ increment a afterwardsa = 5 changes the value of aa = foo() function foo may have side-

effects

Page 92: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.7.6 - TYPE CASTING

Type casting is a way to convert a variable from one data type to another data type. For example, if you want to store a long value into a simple integer then you can type cast long to int. 

Types of Type casting Implicit Conversion:- It does not required

any operator for converted Explicit Conversion:- In c language , Many

conversions, specially those that imply a different interpretation of the value, require an explicit conversion. 92

Page 93: Programming in c

By- Er. Indrajeet Sinha , +919509010997

EXPLICIT CONVERSION EXAMPLE

#include<stdio.h>#include<conio.h> void main() 

{ int i=20;

    double p; clrscr();  p=i; // implicit conversion printf(“implicit value is%d”,p);     getch(); }Output :-

Explicit value is 20.93

Page 94: Programming in c

By- Er. Indrajeet Sinha , +919509010997

IMPLICIT CONVERSION EXAMPLE

#include<stdio.h>#include<conio.h>void main(){      int i=20;      double p;      clrscr();      p=i; // implicit conversion      printf(“implicit value is %d”,p);      getch();} Output :-implicit value is 20. 94

Page 95: Programming in c

INPUT STATEMENT OF C

Lecture no.- 8, UNIT- I

Page 96: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.8- INTRODUCTION OF LECTURE

Definition An input/output statement or io statement is a

portion of a program that instructs a computer how to read and process information. It pertains to gather information from an input device, or sending information to an output device.

In this chapter, we discuss in depth the formatting features of scanf and printf.

These functions input data from the standard input stream and output data to the standard output stream.

Four other functions that use the standard input and standard output—gets, puts, getchar and putchar—were discussed in Chapter 8.

Include the header <stdio.h> in programs that call these functions.

96

Page 97: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.8.1 GETCH()

Function : getch()getch() is used to get a character from console but does

not echo to the screen.Library: < stdio.h>

Declaration: int getch(void);

Example Declaration:char ch;

ch = getch(); (or ) getch();Remarks:getch reads a single character directly from the keyboard,

without echoing to the screen.Return Value:This function return the character read from the keyboard. 97

Page 98: Programming in c

By- Er. Indrajeet Sinha , +919509010997

Example Program:void main()

{

char ch;ch = getch();printf("Input Char Is :%c",ch);

}Program Explanation:Here, declare the  variable ch as  char data type, and then get

a value through getch() library function and store it in the variable ch. And then, print the value of variable ch.During the program execution, a single character is get or read through the getch(). The given value is not displayed on the screen and the compiler does not wait for another character to be typed.And then,the given character is  printed through the printf function. 98

Page 99: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.8.2- GETC()

DescriptionThe C library function int getc(FILE *stream) gets the next

character (an unsigned char) from the specified stream and advances the position indicator for the stream.

 DeclarationFollowing is the declaration for getc() function. int getc(FILE *stream)Parametersstream -- This is the pointer to a FILE object that identifies

the stream on which the operation is to be performed. Return ValueThis function returns the character read as an unsigned

char cast to an int or EOF on end of file or error. 99

Page 100: Programming in c

By- Er. Indrajeet Sinha , +919509010997

Example#include<stdio.h> int main(){ char c;  printf("Enter character: "); c = getc(stdin); printf("Character entered: "); putc(c, stdout); return(0);}Let us compile and run the above program that will produce the

following result: Enter character: aCharacter entered: a 100

Page 101: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.8.3- GETCHAR()

Function : getchar()getchar() is used to get or read the input (i.e a single

character) at run time. Library: <stdio.h>Declaration: int getchar(void);Example Declaration:char ch;

ch = getchar();Return Value:This function return the character read from the keyboard.

101

Page 102: Programming in c

By- Er. Indrajeet Sinha , +919509010997

Example Program:void main()

{

char ch;ch = getchar();printf("Input Char Is :%c",ch);

}Program Explanation Here,declare the  variable ch as  char data type, and then get a

value through getchar()library function and store it in the variable ch.And then,print the value of variable ch. During the program execution, a single character is get or read

through the getchar(). The given value is displayed on the screen and the compiler wait for another character to be typed. If you press the enter key/any other characters and then only the given character is  printed through the printf function. 102

Page 103: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.8.4 GETS()DescriptionThe C library function char *gets(char *str) reads a

line from stdin and stores it into the string pointed to by str. It stops when either the newline character is read or when the end-of-file is reached, whichever comes first.

Declarationchar *gets(char *str)Parametersstr -- This is the pointer to an array of chars where the C

string is stored.Return ValueThis function returns str on success, and NULL on error

or when end of file occurs, while no characters have been read.

103

Page 104: Programming in c

By- Er. Indrajeet Sinha , +919509010997

Example #include <stdio.h> int main() { char str[50]; printf("Enter a string : "); gets(str); printf("You entered: %s", str); return(0); } Result: Enter a string : [email protected] You entered: [email protected] 104

Page 105: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.8.5 GETCHE()Function : getche()getche() is used to get a character from console, and echoes to

the screen.

Library: <Stdio.h>Declaration:int getche(void);

Example Declaration:char ch;

ch = getche();Remarks:

getche reads a single character from the keyboard and echoes it to the current text window, using direct video or BIOS.Return Value:

This function return the character read from the keyboard.105

Page 106: Programming in c

By- Er. Indrajeet Sinha , +919509010997

Example Program:void main()

{

char ch;ch = getche();printf("Input Char Is :%c",ch);

}Program Explanation:

Here,declare the  variable ch as  char data type, and then get a value through getche()library function and store it in the variable ch.And then,print the value of variable ch.

During the program execution, a single character is get or read through the getche(). The given value is displayed on the screen and the compiler does not wait for another character to be typed. Then,after wards the character is  printed  through the  printf function.

106

Page 107: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.8.6- SCANF()

In C programming language, scanf() function is used to read character, string, numeric data from keyboard

Consider below example program where user enters a character. This value is assigned to the variable “ch” and then displayed.

Then, user enters a string and this value is assigned to the variable “str” and then displayed.

107

Page 108: Programming in c

By- Er. Indrajeet Sinha , +919509010997

EXAMPLE PROGRAM FOR SCANF() #include <stdio.h>int main()

{   char ch;   char str[100];   printf("Enter any character \n");   scanf("%c", &ch);   printf("Entered character is %c \n", ch);   printf("Enter any string ( upto 100 character ) \n");   scanf("%s", &str);   printf("Entered string is %s \n", str);}

108

OUtPutEnter any characteraEntered character is aEnter any string ( upto 100 character )haiEntered string is hai

Page 109: Programming in c

By- Er. Indrajeet Sinha , +919509010997

KEY POINT OF SCANF()

The format specifier %d is used in scanf() statement. So that, the value entered is received as an integer and %s for string.

Ampersand is used before variable name “ch” in scanf() statement as &ch.

109

Page 110: Programming in c

OUTPUT STATEMENT OF C

Lecture no.- 9, UNIT- I

Page 111: Programming in c

By- Er. Indrajeet Sinha , +919509010997

In C programming language output functions are the functions through which the result is displayed on the standard output device like monitor.Following are the output functions of C language –

1.9.1- printf( ) – This function is used to print both values of variables and messages. It can also display the character strings. The general syntax is –

printf("Hello world"); printf(" Sum of two numbers is %d",a);

printf("%f,%d",m,a); 111

Page 112: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.9.2 putc() takes a character argument, and outputs it to the specified FILE. fputc() does exactly the same thing, and differs from putc() in implementation only. Most people use fputc().

Example// print the alphabet #include <stdio.h> int main(void) { char i; for(i = 'A'; i <= 'Z'; i++) putchar(i); putchar('\n'); // put a newline at the end to make it pretty return 0; }

112

Page 113: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.9.3 putchar( ) – This function displays the character on the screen which is already inputted by using the getchar( ) function. For ex – putchar(ch); This will display the character which was stored in the variable ch.

1.9.4 puts( ) – It will display the whole string on the screen which user has already inputted by using the gets( ) function. It can also print the message. After printing the string or message it moves the cursor to the next line. It’s syntax is –

puts("Text line or some message") we can also display some text line or message on the screen by using this function with the double quotes

113

Page 114: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.9.5 putch( ) – This function is almost similar to putchar( ) function. It is used to display only one character on the screen which is stored by using getch( ) function. It’s syntax is same as the putchar fucntion but the keyword here used is ‘ putch ‘ instead of putchar.

114

Page 115: Programming in c

SCOPE RULES AND STORAGE CLASSES

Lecture no.- 10, UNIT- I

Page 116: Programming in c

By- Er. Indrajeet Sinha , +919509010997

INTRODUCTION OF LECTURE

Definition:

In C language, each variable has a storage class which decides scope, visibility and lifetime of that variable. 

storage class also determines variable's storage location (memory or registers).

There are four storage classes in C those are automatic, register, static, and external.

116

Page 117: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.10.1 - AUTO STORAGE CLASS

Formal parameters and local variables of functions are variables that are automatically allocated on the stack when a function is called and automatically deallocated when the function returns.

They are of storage class auto.

Page 118: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.10.2 – STATIC STORAGE CLASS

Static variable is allocated and initialized one time, prior to program execution.

It remains allocated until the entire program terminates.

Page 119: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.10.3 – EXTERN STORAGE CLASS Storage class of names known to the linker. Example: extern int square (int x); Means the function will be available to the linker. It notifies the compiler that such a function exists

and that the linker will know where to find it.

Page 120: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.10.4 – REGISTER STORAGE CLASS

If you declare a variable of type register, it simply alerts the compiler to the fact that this memory cell will be referenced more often than most.

Register is a special high-speed memory location inside the central processor.

Page 121: Programming in c

By- Er. Indrajeet Sinha , +919509010997

C STORAGE CLASSES

#include <stdlib.h>

int global_static;static int file_static;

void foo(int auto_param){ static int func_static; int auto_i, auto_a[10]; double *auto_d = malloc(sizeof(double)*5);}

Linker-visible. Allocated at fixed location

Visible within file. Allocated at fixed location.

Visible within func. Allocated at fixed location.

Page 122: Programming in c

By- Er. Indrajeet Sinha , +919509010997

DYNAMIC STORAGE ALLOCATION

What are malloc() and free() actually doing? Pool of memory segments:

Free

malloc( )

Page 123: Programming in c

By- Er. Indrajeet Sinha , +919509010997

SIMPLE DYNAMIC STORAGE ALLOCATION

NextSize

NextSizeSize

Free block Allocated block

malloc( )

First large-enough free block selectedFree block divided into twoPrevious next pointer updatedNewly-allocated region begins with a size value

Page 124: Programming in c

By- Er. Indrajeet Sinha , +919509010997

SIMPLE DYNAMIC STORAGE ALLOCATION

free(a)

Appropriate position in free list identifiedNewly-freed region added to adjacent free regions

Page 125: Programming in c

By- Er. Indrajeet Sinha , +919509010997

FEW TERMS

1. Scope: the scope of a variable determines over what part(s) of the program a variable is actually available for use(active).

2. Longevity: it refers to the period during which a variables retains a given value during execution of a program(alive)

3. Local(internal) variables: are those which are declared within a particular function.

4. Global(external) variables: are those which are declared outside any function.

125

Page 126: Programming in c

By- Er. Indrajeet Sinha , +919509010997

AUTOMATIC VARIABLES Are declare inside a function in which they are to

be utilized. Are declared using a keyword auto. eg. auto int number; Are created when the function is called and

destroyed automatically when the function is exited.

This variable are therefore private(local) to the function in which they are declared.

Variables declared inside a function without storage class specification is, by default, an automatic variable.

126

Page 127: Programming in c

By- Er. Indrajeet Sinha , +919509010997

EXAMPLE PROGRAMint main(){ int m=1000; function2(); printf(“%d\n”,m);}function1(){ int m = 10; printf(“%d\n”,m);}function2(){ int m = 100; function1(); printf(“%d\n”,m);}

127

Output101001000

Page 128: Programming in c

By- Er. Indrajeet Sinha , +919509010997

FEW OBSERVATION ABT AUTO VARIABLES

Any variable local to main will normally live throughout the whole program, although it is active only in main.

During recursion, the nested variables are unique auto variables.

Automatic variables can also be defined within blocks. In that case they are meaningful only inside the blocks where they are declared.

If automatic variables are not initialized they will contain garbage.

128

Page 129: Programming in c

By- Er. Indrajeet Sinha , +919509010997

EXTERNAL VARIABLES These variables are declared outside any function. These variables are active and alive throughout the entire program. Also known as global variables and default value is zero. Unlike local variables they are accessed by any function in the program. In case local variable and global variable have the same

name, the local variable will have precedence over the global one.

Sometimes the keyword extern used to declare these variable. It is visible only from the point of declaration to the end of the program.

129

Page 130: Programming in c

By- Er. Indrajeet Sinha , +919509010997

EXTERNAL VARIABLE (EXAMPLES)int number;float length=7.5;main(){ . . . . . .}funtion1(){. . . . . .}funtion1(){. . . . . .}

130

int count;main(){count=10; . . . . . .}funtion(){int count=0; . . . . . . count=count+1;}

The variable number and length are available for use in all three function

When the function references the variable count, it will be referencing only its local variable, not the global one.

Page 131: Programming in c

By- Er. Indrajeet Sinha , +919509010997

GLOBAL VARIABLE EXAMPLEint x;int main() { x=10; printf(“x=%d\n”,x); printf(“x=%d\n”,fun1()); printf(“x=%d\n”,fun2()); printf(“x=%d\n”,fun3()); }int fun1() { x=x+10; return(x); } int fun2() { int x x=1; return(x); }

131

int fun3() { x=x+10; return(x); }

Once a variable has been declared global any function can use it and change its value. The subsequent functions can then reference only that new value.

Outputx=10x=20x=1x=30

Page 132: Programming in c

By- Er. Indrajeet Sinha , +919509010997

EXTERNAL DECLARATION

int main(){ y=5; . . . . . .}int y;

func1(){ y=y+1}

132

• As far as main is concerned, y is not defined. So compiler will issue an error message.

• There are two way out at this point1. Define y before main.2. Declare y with the storage class

extern in main before using it.

Page 133: Programming in c

By- Er. Indrajeet Sinha , +919509010997

EXTERNAL DECLARATION(EXAMPLES)int main(){ extern int y; . . . . . .}func1(){ extern int y; . . . . . .}int y;

133

Note that extern declaration does not allocate storage space for variables

Page 134: Programming in c

By- Er. Indrajeet Sinha , +919509010997

MULTIFILE PROGRAMS AND EXTERN VARIABLES

int main(){ extern int m; int i . . . . . .}function1(){ int j; . . . . . .}

134

file1.c

int m;function2(){ int i . . . . . .}function3(){ int count; . . . . . .}

file2.c

Page 135: Programming in c

By- Er. Indrajeet Sinha , +919509010997

MULTIFILE PROGRAMS AND EXTERN VARIABLES

int m;int main(){ int i; . . . . . .}function1(){ int j; . . . . . .}

135

file1.c

extern int m;function2(){ int i . . . . . .}function3(){ int count; . . . . . .}

file2.c

Page 136: Programming in c

By- Er. Indrajeet Sinha , +919509010997

STATIC VARIABLES

The value of static variables persists until the end of the program.

It is declared using the keyword static like static int x; static float y;

It may be of external or internal type depending on the place of there declaration.

Static variables are initialized only once, when the program is compiled.

136

Page 137: Programming in c

By- Er. Indrajeet Sinha , +919509010997

INTERNAL STATIC VARIABLE

Are those which are declared inside a function.

Scope of Internal static variables extend upto the end of the program in which they are defined.

Internal static variables are almost same as auto variable except they remain in existence (alive) throughout the remainder of the program.

Internal static variables can be used to retain values between function calls.

137

Page 138: Programming in c

By- Er. Indrajeet Sinha , +919509010997

EXAMPLES (INTERNAL STATIC)

Internal static variable can be used to count the number of calls made to function. eg.

int main(){ int I; for(i =1; i<=3; i++) stat(); }void stat(){ static int x=0; x = x+1; printf(“x = %d\n”,x);}

138

Output

x=1

x=2

x=3

Page 139: Programming in c

By- Er. Indrajeet Sinha , +919509010997

EXTERNAL STATIC VARIABLES

An external static variable is declared outside of all functions and is available to all the functions in the program.

An external static variable seems similar simple external variable but their difference is that static external variable is available only within the file where it is defined while simple external variable can be accessed by other files.

139

Page 140: Programming in c

CONCEPT OF PREPROCESSOR AND MACRO SUBSTITUTION

Lecture no.- 11, UNIT- I

Page 141: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.11.1- INTRODUCTION

The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation.

It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs.

The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process. 141

Page 142: Programming in c

  INTRODUCTION

The C preprocessor executes before a program is compiled.

Some actions it performs are the inclusion of other files in the file being compiled, definition of symbolic constants and macros, conditional compilation of program code and conditional execution of preprocessor directives.

Preprocessor directives begin with # and only white-space characters and comments may appear before a preprocessor directive on a line.

Page 143: Programming in c

 #INCLUDE PREPROCESSOR DIRECTIVE

The #include preprocessor directive has been used throughout this text.

The #include directive causes a copy of a specified file to be included in place of the directive.

The two forms of the #include directive are:#include<filename>

#include "filename" The difference between these is the location the

preprocessor begins searches for the file to be included. If the file name is enclosed in quotes, the preprocessor

starts searches in the same directory as the file being compiled for the file to be included (and may search other locations, too).

Page 144: Programming in c

  #INCLUDE PREPROCESSOR DIRECTIVE

This method is normally used to include programmer-defined headers.

If the file name is enclosed in angle brackets (< and >)—used for standard library headers—the search is performed in an implementation-dependent manner, normally through predesignated compiler and system directories.

Page 145: Programming in c

  #INCLUDE PREPROCESSOR DIRECTIVE

The #include directive is used to include standard library headers such as stdio.h and stdlib.h (see Fig. 5.6) and with programs consisting of several source files that are to be compiled together.

A header containing declarations common to the separate program files is often created and included in the file.

Examples of such declarations are structure and union declarations, enumerations and function prototypes.

Page 146: Programming in c

  #DEFINE PREPROCESSOR DIRECTIVE: SYMBOLIC CONSTANTS

The #define directive creates symbolic constants—constants represented as symbols—and macros—operations defined as symbols.

The #define directive format is #define identifier replacement-text

When this line appears in a file, all subsequent occurrences of identifier that do not appear in string literals will be replaced by replacement-text automatically before the program is compiled.

Page 147: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.11.3 - FUNCTIONS OF A PREPROCESSOR

For More Click Here

147

Page 148: Programming in c

By- Er. Indrajeet Sinha , +919509010997

PREPROCESSOR

All preprocessor directives or commands begin with a #. E.g. #include <stdio.h>

Page 149: Programming in c

By- Er. Indrajeet Sinha , +919509010997

PREPROCESSOR DIRECTIVES

Macro definition #define, #undef

File inclusion #include

Conditional Compilation #if, #ifdef, #ifndef, #elseif, #else

Others

Page 150: Programming in c

By- Er. Indrajeet Sinha , +919509010997

ADVANTAGES

Easy to Develop program Read programs Modify programs

C code more transportable between different machine architectures

Page 151: Programming in c

By- Er. Indrajeet Sinha , +919509010997

#DEFINE

To define constants or any macro substitution.     #define <macro> <replacement name>   E.g.   #define FALSE 0 #define TRUE !FALSE

To undefined a macro. E.g. #undef FALSE A macro must be undefined before being

redefined to a different value.

Page 152: Programming in c

By- Er. Indrajeet Sinha , +919509010997

DEFINE FUNCTIONS

E.g. To get the maximum of two variables:  #define max(A,B) ( (A) > (B) ? (A):(B))

If in the C code:    x = max(q+r,s+t);

After preprocessing:   x = ( (q+r) > (s+t) ? (q+r) : (s+t));

Page 153: Programming in c

By- Er. Indrajeet Sinha , +919509010997

1.11.3.2 FILE INCLUSION

#include directive Include the contents of another file at the point

where the directive appears. Why need file inclusion

Use built-in functions E.g., printf(), rand();

Reuse code

defTime.h

struct date{int day;char

month[10];int year;

};

struct date{int day;char

month[10];int year;

};

struct date today;

#include “defTime.h”→

struct date today;

Your code

Page 154: Programming in c

By- Er. Indrajeet Sinha , +919509010997

FILE INCLUSION FORMATS

#include <file> Used for system header files File contain function prototypes for library functions

<stdlib.h> , <math.h> , etc #include "file"

Used for header files of your own programlooks for a file in the current directory first

then system directories if not found

Page 155: Programming in c

By- Er. Indrajeet Sinha , +919509010997

STANDARD C LIBRARIES

Build-in with your compiler Detailed information

http://www.utas.edu.au/infosys/info/documentation/C/CStdLib.html

stdio.h core input and output capabilities of C

printf functionscanf function

Page 156: Programming in c

By- Er. Indrajeet Sinha , +919509010997

MATH LIBRARY FUNCTIONS

Math library functions perform common mathematical calculations

E.g. exp(), pow(), sqrt(), fabs(), sin(), cos().#include <math.h>

Format for calling functionsFunctionName( argument, …, argument );

All math functions return data type doubleE.g.: printf( "%.2f", sqrt( 900.0 ) ); Arguments may be constants, variables, or

expressions Compile

gcc yourfilename.c –lm –o yourfilename.exe

Page 157: Programming in c

By- Er. Indrajeet Sinha , +919509010997

STDLIB.H

A variety of utility functions rand function

A function to generate a pseudo-random integer number

Return value is in the range 0 to RAND_MAX

Example:#include <stdlib.h> int i = rand();

memory allocation process control