c language presentation=mohit sharma,udaipur

158

Upload: hiudaipur

Post on 18-Nov-2014

110 views

Category:

Documents


0 download

DESCRIPTION

Mohit [email protected] for software development and web site development work,projectscontact mohit sharma=9928686346

TRANSCRIPT

Page 1: C Language Presentation=Mohit Sharma,Udaipur
Page 2: C Language Presentation=Mohit Sharma,Udaipur

• Mohit sharma=9928686346

[email protected]

• Contact for software development and web site development work,projects

Page 3: C Language Presentation=Mohit Sharma,Udaipur

C is a general-purpose, Block structuredBlock structured, ProceduralProcedural, Computer programming languageComputer programming language Developed in 1972Developed in 1972 by Dennis RitchieDennis Ritchie at the Bell Telephone LaboratoriesBell Telephone Laboratories for use with the Unix

Operating System.

[1] It has since spread to many other platforms. Although C was designed as a system implementation language,[2] it is also widely used for applications. C has also greatly influenced many other popular languages,[3] especially C++, which was originally designed as an extension to C.

Page 4: C Language Presentation=Mohit Sharma,Udaipur

Uses of CUses of C

• C was initially used for system development work.

Some examples of the uses of a C might be =

Operating SystemOperating System Language CompilersLanguage Compilers AssemblersAssemblers Text EditorsText Editors Modern ProgramsModern Programs Data BasesData Bases Language InterpretersLanguage Interpreters

Page 5: C Language Presentation=Mohit Sharma,Udaipur

Why C?Why C?

C is simple.C is simple.• C is fast.C is fast.• C offers better interaction with hardwareC offers better interaction with hardware.

Alphabets, Alphabets, digitsdigits

Alphabets, digits, special Alphabets, digits, special symbolssymbols

Words, Words, numbersnumbers

Constants, variables, keywordsConstants, variables, keywords

SentencesSentences Statements or instructionsStatements or instructions

ParagraphParagraph ProgramProgram

ENGLISHENGLISH CC

Page 6: C Language Presentation=Mohit Sharma,Udaipur

History of ANSIHistory of ANSI

• ANSI=American national standard instituteANSI=American national standard institute

• ISO=international standard organizationISO=international standard organization

1960=ALGOL (Arithmetic language)1960=ALGOL (Arithmetic language) 1967=BCPL (Basic combined programming language)1967=BCPL (Basic combined programming language) 1970=B language1970=B language 1972=traditional c1972=traditional c 1978=k & r ’c’1978=k & r ’c’ 1989=ANSI C1989=ANSI C 1990=ANSI / ISO C1990=ANSI / ISO C

Page 7: C Language Presentation=Mohit Sharma,Udaipur

DATA TYPESDATA TYPES

DATA TYPES OF THREE TYPES:

PRIMARY DATA TYPES / FUNDAMENTAL DATA TYPES / BUILT IN PRIMARY DATA TYPES / FUNDAMENTAL DATA TYPES / BUILT IN DATA TYPESDATA TYPES

INTEGER intFLOAT floatCHARACTER charvoid void

• ………………………………………………………………………………………………………………..

USER DEFINEDUSER DEFINED DATA TYPESDATA TYPESTYPEDEFENUM

• ………………………………………………………………………………………………………………

DERIEVEDDERIEVED DATA TYPES DATA TYPES

ARRAYSTRUCTUREUNIONPOINTER

FUNCTIONS

Page 8: C Language Presentation=Mohit Sharma,Udaipur

Integer data Integer data type in ctype in c 8bit8bit IntInt

16 bit16 bit shortshort

32bit32bit longlong

Floating Floating Point data Point data type in ctype in c

Float 32 bit ( 4 byte)

Double 43 bit ( 8 byte)

long double 80 bit ( 10 byte)

Page 9: C Language Presentation=Mohit Sharma,Udaipur

Character data type in cCharacter data type in c

charchar 1byte1byte

signed charsigned char 8bit8bit

unsigned charunsigned char 8bit8bit

DATA TYPEDATA TYPE SIZE(BYTE)SIZE(BYTE) RANGERANGE

CHARCHAR 11 -128 to +128-128 to +128

IntInt 22 -32768 to +32768-32768 to +32768

FloatFloat 44 3.4e-38 to 3.4e+383.4e-38 to 3.4e+38

DoubleDouble 88 1.7e-308 to 1.7e+3081.7e-308 to 1.7e+308

Page 10: C Language Presentation=Mohit Sharma,Udaipur

RULESRULES / / NOTE :NOTE :

C is C is lower case languagelower case language so program are written in so program are written in small lettersmall letter

\n\n is used for go to next line is used for go to next line

for ex:for ex:

ram\nmohanram\nmohan

than result is =than result is =

ramram

mohanmohan

Page 11: C Language Presentation=Mohit Sharma,Udaipur

\t\t is used for text far from its actual position. \b a backspace \r a carriage return (without a line feed) \‘ a single quote (e.g. in a character constant) \" a double quote (e.g. in a string constant) \\ a single backslash

……………………………………………………. we don’t write in program r2

we write r*rr*r……………………………………………………… we use 3.14 in the PLACE of pie…………………………………………………….. Computer is always read right to left.right to left.……………………………………………………. C is case sensitivecase sensitive …………………………………………………….

Page 12: C Language Presentation=Mohit Sharma,Udaipur

Rules:Rules:

ByBy clrscr( );clrscr( ); we can clear the screen, it can used after data type declaration.we use clrscr(); after the data type declaration and before

the printf( ).…………………………………………………………

Always write short form of the data type declarationAlways write short form of the data type declaration• for ex.

kilometer kmkm meter mm parameter papa

Page 13: C Language Presentation=Mohit Sharma,Udaipur

SAVING THE FILESAVING THE FILE

by F2 we can save the program . the another method is to go to file menu

and then save from that position with extension .cand then press ok

………………………………………………………………………………………..

• # include <stdio.h> allows the program to interact with the screen, keyboard and file system of your computer.

• You will find it at the beginning of almost every C program

FullFull FormsForms .h = Extension

Conio = Console input output

conio.h = Console input output system file

stdio = Standard input output

stdio.h = Standard input output system file

Page 14: C Language Presentation=Mohit Sharma,Udaipur

QuestionQuestion

Why all the program will always start with main()?Why all the program will always start with main()?

Ans : bcoz in compiler it is written that translation is start from where main is written that position.Every C program contains a function called main. This is the

start point of the program .

We can not use after main() function any semicolon.

• ………………………………………..

What is the mean of getch ( ) ?What is the mean of getch ( ) ?• Ans: getch is a library function ,by this we can see the output on

screen. if we will not write the getch function in program then the program is not run and we can't see the result.

Page 15: C Language Presentation=Mohit Sharma,Udaipur

Use of some key in the C - languageUse of some key in the C - language

F2 = to save the program F3 = to open the file F5 = to set the screen big and short Ctrl+F9 = to see the resultAlt+F9 = to see the errorF8 = to trace the prog.

Comments in CComments in C

S Single line commentingle line comment //// MMulti line commentulti line comment /* */Note

Comment ignored by compilerComment u can write any where in the programUseful to a person trying to read and understand the

program.

Page 16: C Language Presentation=Mohit Sharma,Udaipur

The format to write the simple programThe format to write the simple program

#include<stdio.h> //HEADER FILE#include<conio.h>void main() / main() //FUNCTION NAME{ //START OF PROGRAMint/float ; //DATA TYPE DECLARATIONclrscr(); //FOR CLEAR SCREEN

printf("\n enter the value of ...");//PROGRAM STATEMENT

scanf("%d"/"%f"/"%c",&...);//TO TAKE VALUE FROM USER

formulaprintf("%d"/"%f"...); //to print outputgetch(); //TO SEE OUTPUT} //END OF PROGRAM

Page 17: C Language Presentation=Mohit Sharma,Udaipur

FlowFlow ChartChart

The flow chart can easy to understand.

Flow chart is a pictorial representation of a algorithm that uses boxes of different shapes to denote different types of instructions.

The logic of all program of flowchart should be from top to bottom and from left to right.

Normally flow lines could not cross each other.

Each symbol except (decision box) used in the flow chart should have one entry point and one exit point.

As far as possible the instructions within the symbol of a program should be independent of any particular programming language.

Page 18: C Language Presentation=Mohit Sharma,Udaipur

Start / StopStart / Stop

ProcessingProcessing

Input /output Input /output /read /write/read /write

ConditionCondition

Flow lineFlow line

connectorconnector

Page 19: C Language Presentation=Mohit Sharma,Udaipur

Example of Flow ChartExample of Flow Chart

Q. Draw a flow chart to calculate 2 number ?

Sum=a+bSum=a+b

StartStart

StopStop

Read a,bRead a,b

Print sumPrint sum

Page 20: C Language Presentation=Mohit Sharma,Udaipur

AlgorithmAlgorithm

• The term algorithm may be formally defined as a sequence of instructions designed in such a way that

• if the instructions are executed in the specified sequence.

• The desired results will be obtained the instructions.

• However should be precise and unambiguous and the result should be obtain after a finite number of execution steps

Page 21: C Language Presentation=Mohit Sharma,Udaipur

• Characteristics of AlgorithmCharacteristics of Algorithm

• Each and every instructions should be precise and unambiguous

• Each instructions should be such that it can be performed in a finite time

• One or more instructions should not be separated infinitely

• After performing the instructions that is after the algorithm terminates the desired result must be obtained.

Page 22: C Language Presentation=Mohit Sharma,Udaipur

Algorithm: To find the area of rectangleAlgorithm: To find the area of rectangle• Step1: Read Length L and breadth b• Step2: Calculate area a = L * b• Step3: Display area• Step4: Stop…………………………………………………………TO FIND WHETHER THE GIVEN NO IS ODD OR EVENTO FIND WHETHER THE GIVEN NO IS ODD OR EVEN

STEP1: READ NO. N• STEP2: CALCULATE REMAINDER R=N%2• STEP3: IF R=0 THEN DISPLAY”NO IS EVEN”• STEP4: IF R=1 THEN DISPALAY “NO IS ODD”• STEP5: STOP

Page 23: C Language Presentation=Mohit Sharma,Udaipur

• ERRORSERRORS

• There are types of errorstypes of errors

Syntax ErrorSyntax ErrorLogical ErrorLogical ErrorRun time ErrorRun time Error

Syntax errorSyntax error when rules or syntax of programming language are not followed

Logical errorLogical error error in planning the programming logic.

RUN TIME ERRORRUN TIME ERROR ERROR COMES WHEN PROGRAM RUNS.

Page 24: C Language Presentation=Mohit Sharma,Udaipur

SoftwareSoftware• software is a set of instructions that directs the computer to process information ,these

instructions are called programs.• without software computer can not work.

Types of software=• System softwareSystem software• Application softwareApplication software

System Software=System Software=the system software contains those programs that control and support the computer system and its data processing applicationsit includes=

• the operating system• the language translators

Operating SystemOperating System• operating system is a organized collection of integrated set of specialized programs that

controls the overall operations of a computer. • it helps the computer to supervise and manage its resources.• operating system calls the application program whenever needed.• translate the special service programs and manages data needed to produced the output as

desired by the users.

Page 25: C Language Presentation=Mohit Sharma,Udaipur

ApplicationApplication SoftwareSoftware Application software is a set of program designed

for a specific uses or application such as word processing ,graphics ,or spreadsheet analysis.

The operating system acts as a communication link between the hardware and the application program.

It is responsible for loading the application software into memory and then staring the program.

When we have finished using application software we return to the operating system.

Page 26: C Language Presentation=Mohit Sharma,Udaipur

PROGRAMMING PROGRAMMING LANGUAGELANGUAGE

A language is a system of communication.

A PROGRAMMING LANGUAGE consists of all symbols ,characters and usage rules that permit people to communicate with computers

A program is a set of logically related instructions that are arranged in a sequence that guides the computer to solve a problem.

The process of writing a program is called programming.

Page 27: C Language Presentation=Mohit Sharma,Udaipur

Machine LanguageMachine Languagethis is a sequence of instructions written in the form of binary numbers consisting of 1's and 0's to which is the computer responds directly.

A machine language has 2parts = the first part is the command or an operation that tells

the computer what functions are to be performed. the second part of the instruction is the operand that tells

the computer where to find or store the data on which the desired operation is to be performed.

the machine language is the only one that computer can understand directly.

so this language is very difficult to understand . but the main advantage of this language is that it is faster

in execution as the computer directly starts executing it.

Page 28: C Language Presentation=Mohit Sharma,Udaipur

Assembly languageAssembly language==

A program written by a programmer in an assembly language is called a Source Program.

After this source program has been converted into machine code by an assembler;

It is referred to as an object program. The main advantage of assembly language is

that the programs written in it are easy to understand as compared to the programs of Machine Language.

for example LDA,7 LOAD REGISTER A WITH 7

Page 29: C Language Presentation=Mohit Sharma,Udaipur

High Level LanguageHigh Level Language

Readability Readability

PortabilityPortability

Easy DebuggingEasy Debugging

Easy Software DevelopmentEasy Software Development

• High Level Language are FORTRAN,COBOL

Page 30: C Language Presentation=Mohit Sharma,Udaipur

FIRMWAREFIRMWARE How does your computer know what to do when u turn it on ?

How does it know to check out your hardware components (such as keyboard and monitor) to see that they have been connected correctly ?

instructions to perform such operations ,

which are critical to the operation of a computer. are stored permanently on a Read Only Memory (ROM) chip installed by the manufacturer inside the computer.

this ROM chip are also called FIRMWARE,

when the power in the computer is turned off.

the instructions stored in ROM are not lost.

Page 31: C Language Presentation=Mohit Sharma,Udaipur

TranslatorTranslator These are system software and program's that are

used to convert assembly or high level language into the Machine Code.

These are also called Language Processors.

Source Program Translator Object Program

TYPES =

AssemblerAssembler

CompilerCompiler

InterpreterInterpreter

Page 32: C Language Presentation=Mohit Sharma,Udaipur

InterpreterInterpreter simple and easy to write.does not require much memory space to store itself translate the program line by line into machine language.

check for the syntax errors line by line and execute each line or statement immediately when statement become error free.

takes less time in translation.

takes more time to execute the program. fast for debugging detection and correction) of syntax and logical

errors.

the object code is produce by an interpreter is not saved for future reference.

Page 33: C Language Presentation=Mohit Sharma,Udaipur

CompilerCompiler

Complex and difficult to write. Requires large memory space to store itself. Translate the entire program into machine language at

once. Checks the syntax errors in the program and when the

whole program becomes error free than it is translated into machine code and executed.

Takes more time in translation. Takes less time to execute the program Slow for debugging.

The object code produce by the compiler is saved for the future reference.

Page 34: C Language Presentation=Mohit Sharma,Udaipur

TestingTesting andand DebuggingDebugging

TestingTesting

Completes when all desired verification against specification have been performed.

Testing can be planned

Testing can begin at early stages.

Page 35: C Language Presentation=Mohit Sharma,Udaipur

DebuggingDebugging

Programming errors are removed.

Completes when there are no known errors.

Cannot be planned ahead of time.

Cannot begin until the end of development Cycle.

Page 36: C Language Presentation=Mohit Sharma,Udaipur

Program Development Life CycleProgram Development Life Cycle

It is divided into the following phases= Defining the problem. Designing the program. Coding the program. Documenting the program. Implementing and Maintaining the

program.

Page 37: C Language Presentation=Mohit Sharma,Udaipur

DocumentationDocumentation==

System documentation involves collecting, organizing, storing, and otherwise maintaining a complete historical record of program and other documents used or prepared the different phases of the SDLC.

• Uses of DocumentationUses of Documentation==

easier maintenance

avoid duplication

Page 38: C Language Presentation=Mohit Sharma,Udaipur

CHARACTER SETCHARACTER SET C character set includes the

LETTERS= UPPER CASE (A-Z) LOWER CASE (a-z) digits (0 - 9) special character

White spaces=• BLANK SPACES HORIZONTAL TAB NEW LINE FORM FEED

• alphanumeric ,digits, and special symbol

Page 39: C Language Presentation=Mohit Sharma,Udaipur

Escape Sequence Character in CEscape Sequence Character in C

character Escape sequence character

bell \aback space \bhorizontal tab \tvertical tab \vform feed \fcarrier return \rback slash \\null \0question mark \?

Page 40: C Language Presentation=Mohit Sharma,Udaipur

CC TOKENSTOKENS

KEYWORD

( RESERVED WORD )

(EX. FLOAT ,WHILE)

CONSTANTS (15.5,100)

STRINGS ("ABC","YEAR")

SPECIAL SYMBOL ([ ],{ })

OPERATORS ( + - * , )

IDENTIFIER /

VARIABLE NAME

Page 41: C Language Presentation=Mohit Sharma,Udaipur

CONSTANTS IN CCONSTANTS IN C== Constant=quantity that does not change

• Constant are of 2 types=Constant are of 2 types=• primary constant• secondary constants• -----------------------------------------------------------------------------

• Primary constant-Primary constant-• integer constant• real (FLOAT) constant• ----------------- -----------------------------------------------------------------

• Character constantCharacter constant• SINGLE • STRING• ------------------------------------------------------------------------------------------

Page 42: C Language Presentation=Mohit Sharma,Udaipur

• Secondary ConstantSecondary Constant• ArraysArrays• PointerPointer• Structure Structure • Enum Enum • UnionUnion

• ==============================Integer ConstantInteger Constant==

It must have at least one digit.It must have at least one digit.• Must not have a decimal point.Must not have a decimal point.• It can be either positive or negative but default is It can be either positive or negative but default is

positive.positive.• No commas and blanks are allowed.No commas and blanks are allowed.

Page 43: C Language Presentation=Mohit Sharma,Udaipur

Integer constant are of three types=Integer constant are of three types=

(1) Decimal integer = consists of a set of digits 0 through 9231, - 333, +55,0, 47777------------------------------------------------------------------------------------------------------------------------(2) Octal integer = Consist of any combination of digits from the set 0 through 7 with a

leading zero .for ex. 0551, 037----------------------------------------------------------------------------------------------------------------------(3) Hexadecimal integer= Represent A through F,------------------------------------------------------------------------------------------------------------------------

Real constants (floating point Constants)a) fractional form=it must have at least one digit and a decimal point.

could be negative and positive.-------------------------------------------------------------------------------------------------------------b) exponent form=

< mantissa > e < exponent >exponent is always in the integer formand mantissa is always in the fractional form--------------------------------------------------------------------------------------------------------------

character constant=single alphabet or digit or special symbol enclosed within single inverted commas.

Page 44: C Language Presentation=Mohit Sharma,Udaipur

VariableVariable==Name given to the location in the memory where this constant is stored.Name given to the location in the memory where this constant is stored.

• 2 X + 3 Y = 332 X + 3 Y = 33• Here X and Y is variable Here X and Y is variable • here 2 ,3,33 are constanthere 2 ,3,33 are constant

Rules Rules for Constructingfor Constructing VARIABLEVARIABLE / / IDENTIFIER IDENTIFIER N Namesames

first character must be alphabet or underscore(_)first character must be alphabet or underscore(_)

must consist of letters, digits, underscore(_)must consist of letters, digits, underscore(_)

keyword /reserve word are not allowed.keyword /reserve word are not allowed.

uppercase and lower case are identicaluppercase and lower case are identical

must not contain white spacesmust not contain white spaces.

Page 45: C Language Presentation=Mohit Sharma,Udaipur

• CC keyword and Reserve Wordkeyword and Reserve Word==

• The words whose meaning has already been explained to the c compiler are The words whose meaning has already been explained to the c compiler are known as keyword the keywords can not be use as variable names.known as keyword the keywords can not be use as variable names.

Standard keyword/Reserve Word in CStandard keyword/Reserve Word in C• Auto Auto breakbreak casecase• CharacterCharacter countcount continuecontinue• DefaultDefault dodo doubledouble• ElseElse enumenum externextern• FloatFloat forfor gotogoto• IfIf longlong registerregister• ReturnReturn `̀ signsign signofsignof• StaticStatic struct struct switchswitch• TypedefTypedef unionunion unsignunsign• VoidVoid volatilevolatile whilewhile

Page 46: C Language Presentation=Mohit Sharma,Udaipur

C operatorsC operators =

ARITHMATIC OPERATORARITHMATIC OPERATOR RELATIONAL OPERATORRELATIONAL OPERATOR LOGICAL OPERATORLOGICAL OPERATORASSIGNMENTASSIGNMENT INCREMENT (++)INCREMENT (++) DECREMENT (--)DECREMENT (--) CONDITIONAL (IF,ELSE)CONDITIONAL (IF,ELSE) BITWISEBITWISE COMMA ( ,)COMMA ( ,) SIZEOF( ) C COMPILE TIMESIZEOF( ) C COMPILE TIME POINTER OPERATOR (*.&)POINTER OPERATOR (*.&)

Page 47: C Language Presentation=Mohit Sharma,Udaipur

COMMA COMMA OPERATOROPERATOR

• Sum=(x=20,y=30,x+y)Sum=(x=20,y=30,x+y)• Expressions are evaluated left to right and the value of rightmost Expressions are evaluated left to right and the value of rightmost

expressions is the value of the combined expressionexpressions is the value of the combined expression.----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

SizeofSizeof Operator Operator (Compile time operator) (Compile time operator)

• Returns the number of bytes the operand occupies

• Used to determine the length of array and structure when their sizes are not known to the programmer

• Used to allocate memory space dynamically to variable during execution of a program

• Also known as compile time operator.

Page 48: C Language Presentation=Mohit Sharma,Udaipur

TernaryTernary / / ConditionalConditional OperatorOperator

• C includes a very special operator called the ternary or conditional operatorIt is called ternary because it uses three operand

• The ternary operator acts like a short hand version of the ternary operator is

• Expression1: expression2:expression3

• Example:If (first>second)Max=first;ElseMax=second;

The above statement can be written asMax=(first>second) first: second;

Page 49: C Language Presentation=Mohit Sharma,Udaipur

The ? : operatorThe ? : operator• C language has a special operator, useful for making two way

decisions .• This operator is a combinational of ? And : takes three

operands.• This operator is popularly known as conditional operator or

ternary operator• The general form of conditional operator is as follows:• Conditional expression ?<expression1>:<expression2>• The conditional expression is evaluated first.• If the result is true, expression 1 is evaluated and returned as

the value of the conditional expression.• Otherwise expression 2 is evaluated and its value is returned .• In general conditional operator is used as substitute for simple

if…else Statement

Page 50: C Language Presentation=Mohit Sharma,Udaipur

• Consider the following code:• int a=10;• Int b=20;• Int c;

If (a>b)c=a;

elsec=b;

• This code segment can be written as follows using ternary operator

C=(a>b) ? a: b

Page 51: C Language Presentation=Mohit Sharma,Udaipur

UnaryUnary OperatorOperator

• - ++ -- ! * & sizeof (type)

• C includes a class of operators that act upon a single operand to produce a new value such operator are unary operator

Page 52: C Language Presentation=Mohit Sharma,Udaipur

ArithmeticArithmetic OperatorOperator

OperatorOperator meaningmeaning

++ AdditionAddition

-- Subtraction Subtraction

** MultiplicationMultiplication

// DivisionDivision

%% Module divisionModule division

Page 53: C Language Presentation=Mohit Sharma,Udaipur

RelationalRelational OperatorOperator

OPERATOROPERATOR MEANINGMEANING

<< IS LESS THANIS LESS THAN

>> GREATER THANGREATER THAN

>=>= Greater than equal toGreater than equal to

<=<= Less than equal toLess than equal to

==== Equal toEqual to

!=!= Not equal to Not equal to

Page 54: C Language Presentation=Mohit Sharma,Udaipur

LogicalLogical OperatorOperator

OperatorOperator MeaningMeaning

&&&& ANDAND

|||| OROR

!! NOTNOT

Page 55: C Language Presentation=Mohit Sharma,Udaipur

Assignment OperatorsAssignment Operators

• The assignment operator = assigns a value to a variable. • For example, • x = 1 sets x to 1, • and a = b sets a to whatever b's value is.• We've called the = sign the ``assignment operator'' and

referred to ``assignment expressions'' because, in fact, = is an operator just like + or -.

• C does not have ``assignment statements''; instead, an assignment like a = b is an expression and can be used wherever any expression can appear.

Page 56: C Language Presentation=Mohit Sharma,Udaipur

• Since it's an expression, the assignment a = b has a value, namely, the same value that's assigned to a. This value can then be used in a larger expression;

• for example, we might write

• c = a = b which is equivalent to c = (a = b) and assigns b's value to both a and c.

• (The assignment operator, therefore, groups from right to left.).

Page 57: C Language Presentation=Mohit Sharma,Udaipur

BITWISE BITWISE OPERATOROPERATOR

OPERATOROPERATOR MEANINGMEANING

&& BITWISE ANDBITWISE AND

|| BITWISE ORBITWISE OR

^̂ BITWISE EXCLUSIVE BITWISE EXCLUSIVE OROR

<<<< SHIFT LEFTSHIFT LEFT

>>>> SHIFT RIGHTSHIFT RIGHT

Page 58: C Language Presentation=Mohit Sharma,Udaipur

• INCREMENTINCREMENT & & DECREMENT OPERATOR DECREMENT OPERATOR

• + + and - - are the increment and decrement operator

• + + adds 1 to the operand

• -- subtract 1

• + + and – - -are unary operator and takes the following form

• + + i or I + +

• - - i or I - -----------------------------------------------------------------------------------------------------------

• + + i • I = I + 1• I + = 1 are equivalent--------------------------------------------------------------------------------------------------------• -- i• I = I - 1• I - = 1 are equivalent---------------------------------------------------------------------------------------------------------

Page 59: C Language Presentation=Mohit Sharma,Udaipur

Control Structure in CControl Structure in C

Conditional statementConditional statement» If-elseIf-else

» Else-ifElse-if

» switch caseswitch case

UNCONDITIONAL STATEMENTUNCONDITIONAL STATEMENT

• While STATEMENTWhile STATEMENT• Do whileDo while• for STATEMENTfor STATEMENT• jumpjump• continuecontinue• breakbreak• gotogoto

Page 60: C Language Presentation=Mohit Sharma,Udaipur

if -elseif -else

• The first statement or block of statements The first statement or block of statements is executed if the condition is executed if the condition isis true, true,

• and the second statement or block of and the second statement or block of statements (following the keyword else) is statements (following the keyword else) is executed if the condition is executed if the condition is notnot true. true.

Page 61: C Language Presentation=Mohit Sharma,Udaipur

• While loopWhile loop

• The while loop continues to loop until the conditional expression The while loop continues to loop until the conditional expression becomes false. The condition is tested upon entering the loop. becomes false. The condition is tested upon entering the loop.

• Loops generally consist of one or more Loops generally consist of one or more control expressionscontrol expressions which which control the execution of the loop, and the control the execution of the loop, and the bodybody, which is the statement , which is the statement or set of statements or set of statements

• The most basic The most basic looploop in C is the while loop. A while loop has one in C is the while loop. A while loop has one control expression, and executes as long as that expression is true. control expression, and executes as long as that expression is true.

• The general syntax of a while loop is The general syntax of a while loop is • while( while( expressionexpression ) ) statementstatement A while loop starts out like an if A while loop starts out like an if

statement: if the condition expressed by the statement: if the condition expressed by the expressionexpression is true, the is true, the statementstatement is executed. is executed.

• However, after executing the statement, the condition is tested again, However, after executing the statement, the condition is tested again, and if it's still true, the statement is executed again. (As long as the and if it's still true, the statement is executed again. (As long as the condition remains true, the body of the loop is executed over and over condition remains true, the body of the loop is executed over and over again. (If the condition is false right at the start, the body of the loop again. (If the condition is false right at the start, the body of the loop is not executed at all.)is not executed at all.)

Page 62: C Language Presentation=Mohit Sharma,Udaipur

do.. whiledo.. while STATEMENTSTATEMENT

do while is a exit control looping structure.do while is a exit control looping structure. that is loop body will be executed first before evaluating loop control statement.that is loop body will be executed first before evaluating loop control statement.

do while takes the following forms.do while takes the following forms.

initialization of loop control variable:initialization of loop control variable:

dodo{{ body of the loop;body of the loop;....................................................

}}While (test condition)While (test condition)statement x;statement x;

Page 63: C Language Presentation=Mohit Sharma,Udaipur

do whiledo while

once the program get to the do statement the program proceeds executing the statements in the loop body ,and once it reaches the end of the loop body, it evaluates the test condition.

if test condition returns true, the loop body is executed once again and again the test condition is evaluated once the loop body finishes the execution.the repeated execution of the loop body continues as long as the test condition returns true.

the loop get terminated once the test condition returns false and the program control is passed to the statement that is next to the loop control.

Page 64: C Language Presentation=Mohit Sharma,Udaipur

for statementfor statement

the for statement is the most popular and more concise loop control structure supported by almost all the programming languages.for is an entry control looping structure.for is quite efficient looping structure when compared while or do while because it takes cares of initialization of loop control variable evaluating loop control statement, increasing /decreasing the value of loop control variable.the execution of the loop control variable is done first ,using assignment statement such as i=1, or count =10 etc, here i and count are referred as loop control variables,

Page 65: C Language Presentation=Mohit Sharma,Udaipur

the value of the loop control variable is tested using test condition.

the test condition is a relational or logical expression such as i<10 or (i<10)&&(k>=0) etc.the test condition is used to direct the execution of the loop body

if the test condition n is true the body of the loop will be get executed otherwise the loop will be get terminated and the execution follows to the next statement that immediately follows the loop.

Page 66: C Language Presentation=Mohit Sharma,Udaipur

when the loop body completes the execution the control is passed back to the for statement

and then the value of the control variable is incremented /decremented and tested against the test condition.to see whether it satisfies the test condition.if the test condition is satisfied that is if the loop condition returns true, the loop body will get executed once again.

the process of repeated execution continue till the value of the loop control variable fails to satisfies the loop condition

Page 67: C Language Presentation=Mohit Sharma,Udaipur

C Basic ProgramsC Basic Programs

write a c program to print ur name?

#include<stdio.h> #include<conio.h> void main(){ int a,b; clrscr(); printf("my name is MOHIT SHARMA \n3 k 21"); getch();}

Page 68: C Language Presentation=Mohit Sharma,Udaipur

// (print positive –negative )

#include<stdio.h>#include<conio.h>

void main( ){int n;clrscr();printf("enter n");scanf("%d",&n);

if(n>0){printf("positive value");}else{printf("negative value");}

getch();

}

Page 69: C Language Presentation=Mohit Sharma,Udaipur

// (voting program)

#include<stdio.h>#include<conio.h>

void main()

{int age;clrscr();printf("enter age");scanf("%d",&age);

if(age>18)

{printf("u can vote");}

else{printf(“ u r child ");}getch();}

Page 70: C Language Presentation=Mohit Sharma,Udaipur

// // A A AND AND B B WHICH WHICH IS IS MAX MAX

#include<stdio.h>#include<conio.h>

void main(){int a,b;clrscr();printf("enter a,b");scanf("%d%d",&a,&b);if(a>b){printf("a is max");}else{printf("b is max");}

getch();

}

Page 71: C Language Presentation=Mohit Sharma,Udaipur
Page 72: C Language Presentation=Mohit Sharma,Udaipur

• FEATUES OF POINTERFEATUES OF POINTER

• POINTERPOINTER which points address of a variablewhich points address of a variable

• Pointer Operator * , &* , &

1.1. pointers are more efficient in handling arrays and data table.pointers are more efficient in handling arrays and data table.

2.2. use to return multiple values from function.use to return multiple values from function.

3.3. pointer allow and support dynamic memory management.pointer allow and support dynamic memory management.

4.4. pointers use for manipulating dynamic data structure such as link list, queue, pointers use for manipulating dynamic data structure such as link list, queue, stack, graph.stack, graph.

5.5. pointer reduce complexity of program.pointer reduce complexity of program.

6.6. pointer increase the execution speed of the program.pointer increase the execution speed of the program.

7.7. pointer reduce the program execution timepointer reduce the program execution time

Page 73: C Language Presentation=Mohit Sharma,Udaipur

• Rules for Pointer OperationRules for Pointer Operation

• A Pointer variable can be assigned the address of another variable.

• A Pointer variable can be assigned the values of another pointer variable

• A Pointer variable can be initialize with zero or null.

• A Integer value can be subtracted or added from pointer variable.

• 2 Pointers variables can not be added.

• When 2 pointer point the same array one pointer variable can be subtracted from the another variable.

• A Pointer variable can be used increment and decrement operator.

Page 74: C Language Presentation=Mohit Sharma,Udaipur

“String HandlingString Handling Function Function in Cin C""

strlen( )strlen( ) calculates length of a stringcalculates length of a string

strcpy( )strcpy( ) copy the contents of one string into anothercopy the contents of one string into another

strcmp( )strcmp( ) Used to compare to stringUsed to compare to string

strlwr( )strlwr( ) Convert all characters in the given string Convert all characters in the given string from upper case to lower casefrom upper case to lower case

strrev( )strrev( ) Rearrange all character in the given string Rearrange all character in the given string in reverse orderin reverse order

Strcat( )Strcat( ) Used to add two given stringsUsed to add two given strings

Strupr( )Strupr( ) Convert all characters in the given string Convert all characters in the given string from lower case to upper casefrom lower case to upper case

Page 75: C Language Presentation=Mohit Sharma,Udaipur

Header file =Header file =

The c standard library contains files containing the standard functions that ur program may use these files are known as header files

<ctype.h><ctype.h> Character class testCharacter class test

<error.h><error.h> Error codes reported by some library Error codes reported by some library functionfunction

<float.h><float.h> Implementations defined floating point Implementations defined floating point limits.limits.

<limits.h><limits.h> Implementation defined limitsImplementation defined limits

<locale.h><locale.h> Locale specific informationLocale specific information

Page 76: C Language Presentation=Mohit Sharma,Udaipur

< stdio.h >< stdio.h > Input and OutputInput and Output

< stdlib.h >< stdlib.h > Utility FunctionsUtility Functions

< string.h >< string.h > String FunctionsString Functions

< time.h >< time.h > Time and Date FunctionTime and Date Function

< signal.h >< signal.h > SignalsSignals

< math.h >< math.h > Mathematical FunctionMathematical Function

Page 77: C Language Presentation=Mohit Sharma,Udaipur

Modular ProgrammingModular Programming==

Modular Programming is a strategy applied to the design and development of software system.

It is defining as organizing large program into small program.

Into small independent program segment called modules.

Some Characteristics of Modular ProgrammingSome Characteristics of Modular Programming

Each module should do only one thing.

Communication between module is allot only by calling a module.

A module can be call by one and only one higher module.

All module design a single entry and single exit.

Page 78: C Language Presentation=Mohit Sharma,Udaipur

Executing a c programExecuting a c program

Creating the programCreating the program Compiling the programCompiling the program Linking the programLinking the program Executing the programExecuting the program

BASIC structure of c programBASIC structure of c program

DOCUMENTATION SECTIONDOCUMENTATION SECTION LINK SECTIONLINK SECTION DEFINITION SECTIONDEFINITION SECTION GLOBAL DECLARATION SECTIONGLOBAL DECLARATION SECTION MAIN FUNCTION SECTION MAIN FUNCTION SECTION SUB PROGRAM SECTIONSUB PROGRAM SECTION

Page 79: C Language Presentation=Mohit Sharma,Udaipur

• Documentation sectionDocumentation section

consist of a set of comment lines giving the name of the program consist of a set of comment lines giving the name of the program the author or programmer and other detailsthe author or programmer and other details

• Link sectionLink section

provides instructions to the compiler to link functions from the system provides instructions to the compiler to link functions from the system librarylibrary

• Definition sectionDefinition section

defines all symbolic constantsdefines all symbolic constants..

• Global declarationGlobal declaration

global variables and user define functionglobal variables and user define function

• main() function (declaration and executable part)main() function (declaration and executable part)

declaration part declares all the variables used in the executable part declaration part declares all the variables used in the executable part that consist of group of statements.that consist of group of statements.

• Subprogram section (user defined functionSubprogram section (user defined function))

contains all the user define functions called in the main program of the contains all the user define functions called in the main program of the function.function.

Page 80: C Language Presentation=Mohit Sharma,Udaipur
Page 81: C Language Presentation=Mohit Sharma,Udaipur

AN AN ARRAYARRAY IS AIS A : :collection of data element that are of identical data typecollection of data element that are of identical data typestored in consecutive memory locations and are referred by a common stored in consecutive memory locations and are referred by a common name.name.till now in our programs we've seen variables which can store only one till now in our programs we've seen variables which can store only one value at any given point of time,. value at any given point of time,. but it is often required in programming that u may need to store a but it is often required in programming that u may need to store a group of values in one variable.group of values in one variable.for examplefor exampleu want to store marks obtained by 100 students of the class in a u want to store marks obtained by 100 students of the class in a particular subject particular subject or u want to store name of a 100 student which is of 10 character in or u want to store name of a 100 student which is of 10 character in length.length.but where as an integer or characters variable can store only value at a but where as an integer or characters variable can store only value at a given point of time,given point of time,in such sought of cases arrays come in handy for the programmer.in such sought of cases arrays come in handy for the programmer.

Page 82: C Language Presentation=Mohit Sharma,Udaipur

for ex. if we want to store marks of 100 students instead of declaring 100 variables u can declare a special kind of variable called array in the following manner

int marks[100] ;

now marks is an array which can store 100 integer values.if u want to store name of a student which is of 15 character in length, u can declare a character array in the following form.char name[15] ;now name is an array which is capable of storing 15 character values.u can arrays for all the data type that are supported by C.

Page 83: C Language Presentation=Mohit Sharma,Udaipur

Declaring an ArrayDeclaring an Array

like any other variables arrays must be declared before they are used like any other variables arrays must be declared before they are used

the general form of array declaration is the general form of array declaration is type variable-name[size]type variable-name[size]

the type specifies the data type of the element in an arraythe type specifies the data type of the element in an arrayvariable name specifies the name of the arrayvariable name specifies the name of the arraysize specifies the no. of elements going to be stored in an array.size specifies the no. of elements going to be stored in an array.

for ex.for ex.int arr[5];int arr[5];now we have created an array that can store 5 integer values.now we have created an array that can store 5 integer values.

Page 84: C Language Presentation=Mohit Sharma,Udaipur

Memory Representation of Array Memory Representation of Array

for ex.for ex.int arr[5];int arr[5];now we have created an array that can store 5 integer values.now we have created an array that can store 5 integer values.

all the elements of the array gets stored in consecutive memory locations.all the elements of the array gets stored in consecutive memory locations.

in the above ex. we have declared an array that can stored 5 integer valuesin the above ex. we have declared an array that can stored 5 integer valuessuppose the first element of the array is stored in 80th address location then the suppose the first element of the array is stored in 80th address location then the second element gets stored in 82th ,second element gets stored in 82th ,third in 84th ,third in 84th ,fourth in 86th and fifth in 88th address location fourth in 86th and fifth in 88th address location (remember each integer occupies 2bytes of storage in memory ,that is why address (remember each integer occupies 2bytes of storage in memory ,that is why address

locations are 80,82,84,86,88locations are 80,82,84,86,88))

Page 85: C Language Presentation=Mohit Sharma,Udaipur

the above statement int arr [5] creates an array in the following manner in the above statement int arr [5] creates an array in the following manner in computer memorycomputer memory

Size of an array:Size of an array:

U can find the size of an array ,by performing following U can find the size of an array ,by performing following computation.computation.

No of elements in an array *size of an arrayNo of elements in an array *size of an array

Hence the size of the array int arr [5] would be 5 * sizeof (int)Hence the size of the array int arr [5] would be 5 * sizeof (int)

That is 5*2=10 bytes (size of an int type on a 16bit machine is 2 That is 5*2=10 bytes (size of an int type on a 16bit machine is 2 bytes.)bytes.)

Page 86: C Language Presentation=Mohit Sharma,Udaipur

Initialize an arrayInitialize an arrayWe can initialize the element of array either at the time of declaration or any where else in the We can initialize the element of array either at the time of declaration or any where else in the program .program .

Some of the general forms of the initializing an array are as followsSome of the general forms of the initializing an array are as follows

Initializing an array elements at the time of declaration Initializing an array elements at the time of declaration

Int arr[5]={42, 13 ,87 ,76 ,54};Int arr[5]={42, 13 ,87 ,76 ,54};

Initialize an array element after declarationInitialize an array element after declaration

Int arr[5];Int arr[5];

arr[0]=42;arr[0]=42;

arr[1]=13;arr[1]=13;

arr[2]=87;arr[2]=87;

arr[3]=76;arr[3]=76;

arr[4]=54;arr[4]=54;

Page 87: C Language Presentation=Mohit Sharma,Udaipur

Code for initializing elements of array by accepting values from Code for initializing elements of array by accepting values from keyboardkeyboard

Int arr[5];

Int i;

For (i=0; i<5; i++)

{

Scanf (“ %d ”, & arr [i] );

}

Page 88: C Language Presentation=Mohit Sharma,Udaipur

Array in memory after initializationArray in memory after initialization

42 13 87 76 54

Value stored in an array

Addresses of an individual element in an array

Page 89: C Language Presentation=Mohit Sharma,Udaipur

Referring to the elements of an arrayReferring to the elements of an array

The main thing after declaring and initializing an array is how to The main thing after declaring and initializing an array is how to access the individual element of an array.access the individual element of an array.

If u observe, while initializing elements of an array we have used If u observe, while initializing elements of an array we have used arr[0],arr[1]…. and so on.arr[0],arr[1]…. and so on.

From that we got a little bit of idea on how to refer to individual From that we got a little bit of idea on how to refer to individual element of an array.element of an array.

We can access or refer to the individual elements of an array We can access or refer to the individual elements of an array through their position or location in the array.through their position or location in the array.

The position or location of an element in an array is commonly The position or location of an element in an array is commonly referred as array subscript.referred as array subscript.

An array subscript always starts from().An array subscript always starts from().

Page 90: C Language Presentation=Mohit Sharma,Udaipur

That is the first element of an array can be referred as arr[0],

Second element can be referred as arr[1]

Third element is referred as arr[2]

And so on ………

42 13 87 76 54

Page 91: C Language Presentation=Mohit Sharma,Udaipur

Storage class in CStorage class in CAutomatic storage class,Automatic storage class,

local variable known to only to the function in local variable known to only to the function in which it is declared .default is auto.which it is declared .default is auto.

autoauto

Register storage classRegister storage class

Local variable which is stored in registerLocal variable which is stored in register registerregister

Static storage classStatic storage class

Local variable which exists and retains its Local variable which exists and retains its value even after the control is transferred to value even after the control is transferred to the calling function.the calling function.

staticstatic

External storage classExternal storage class

Global variable known to all functions in the Global variable known to all functions in the file. file.

externextern

Page 92: C Language Presentation=Mohit Sharma,Udaipur

User defined type declarationUser defined type declaration• C support a feature known as type definition” that

allows users to define an identifier that would represent an existing data type.

• The user define data type identifier can later be used to declare variables.It takes a general form:

typedef type identifier;• Where type refers to an existing data type and

“identifier “ refers to the “new” name given to the data type.

• The existing data type may belongs to any class of type, including the user defined ones.

• Remember that the new type is new only in name, but not the data type .

• typedef cannot create a new type.

Page 93: C Language Presentation=Mohit Sharma,Udaipur

• Some examples of type definition are:Some examples of type definition are:

typedef int units;typedef float marks;

• Here unit symbolizes int and marks symbolizes float.• They can be later used to declare variables as follows:

Units batch1,batch2;marks name1[50],name2[50] ;

• Batch1 and batch2 are declared as int variable and name[50] and name2[50] are declared as 50 element floating point array variable.

• The main advantage of typedef is that we can create meaningful data type names for increasing readability of the program.

• Another user defined data type is enumerated data type provided by ANSI standard .

• It is defined as follows.

Page 94: C Language Presentation=Mohit Sharma,Udaipur

FUNCTIONFUNCTION

Page 95: C Language Presentation=Mohit Sharma,Udaipur

UUser Define Functionser Define Function

the use of user define function allows a large program to be broken down into a no of smaller self content component.

c program can be modular with the use of a function.for ex.

many program require that a particular group of instructions be access repeatedly from several different places with in the program

the repeated instructions can be placed with in a single function which can then be accessed whenever it is needed.

Page 96: C Language Presentation=Mohit Sharma,Udaipur

The use of function avoids the need of redundant programming in the same instructions=

a function is a self content program segment.

every program consist of one or more function.

one of the function must be call a main function.

if program contain multiple function then there definition may be in any order.

the same function can be access from several different places with in a program.

Page 97: C Language Presentation=Mohit Sharma,Udaipur

Function TerminologyFunction Terminology

function definition=

formal parameter

actual parameter

function name

calling a function

prototype of a function (function declaration)

Page 98: C Language Presentation=Mohit Sharma,Udaipur

call by value

call by reference

Recursion (function call by itself)

function with argument but no return value

function with argument but return value

function with no argument and no return value.

function returns multiple values.

Page 99: C Language Presentation=Mohit Sharma,Udaipur

functionuser defined function

primitive functionmath.h

•abs()

•log()

sqr()

•exp()

cos()

sin()

Page 100: C Language Presentation=Mohit Sharma,Udaipur

• Some points Regarding to the RecursionSome points Regarding to the Recursion

• when function call by itself is called recursion

• in order to solve a problem recursively to condition must be satisfied.

• the problem must be return in recursive form

• the problem statement must include a stopping condition.• when recursive function is executed the function call are not

executed immediately they are placed on the stack.

• the tower of Hanoi is a good illustration example for the recursion technique.

Page 101: C Language Presentation=Mohit Sharma,Udaipur

CATEGORY OF FUNCTIONCATEGORY OF FUNCTION

category 1 = function with no argument no return value

category 2 = function with argument no return value.

category 3 = function with argument but return value.

category 4 = function with no argument but return value.

category 5 = function that return a multiple values.

Page 102: C Language Presentation=Mohit Sharma,Udaipur

FunctionFunctionA function is a self contained block of statements that have been given a name and performs different task of some kind.

Why we need functions ?Why we need functions ?• most real programs are much larger than the small samples we have looked at.• c follows procedural approach towards programming and hence , functions play a

major role in program development.

Advantages of using functions =Advantages of using functions =• function supports top down approach towards programming.

• The length of the source program can be reduced by using functions at appropriate places.

• This factor is particularly important when functions are having limited memory.

• Function support reusability of code.

• A function once written ,compiled and packaged into a library can be reused in many other program without rewriting the code.

Page 103: C Language Presentation=Mohit Sharma,Udaipur

C functionsC functions can be classified into two categories can be classified into two categories : :

• Library functionsLibrary functions

• User defined functionsUser defined functions

• The basic difference between the two is =

• Library are prewritten, compiled packaged into Header files and are made as a part of c standard library.

• The functions like printf (), scanf () etc. are a part of C Standard Library,

• Where as an user defined functions needs to be written by the programmer according to the requirements of the application he is developing.

Page 104: C Language Presentation=Mohit Sharma,Udaipur

User Defined FunctionsUser Defined Functionsfor example:

# include < stdio.h >int square( int) ; //function prototypemain ( ) //calling function { int num, s; printf (“enter a no for which u want to find square \n ”) ; scanf ( “ %d ” & num) ; s=square (num) ; //called function printf ( “square of %d is %d \n “ num , s );} int square (int i) //function definition (header){ return i*i ; //function definition( body)}

Page 105: C Language Presentation=Mohit Sharma,Udaipur

Function PrototypeFunction Prototype A function prototype provides the basic information that compiler

needs to check that a function is being used correctly or not in the program.

The function prototype specifies the following : Type of the return value:

for ex. (int /float/char)• Function nameFunction name

for ex. sum , multiply , divide etc.• Number order and types of the argument passed to the functionNumber order and types of the argument passed to the function

• Essentially the same information as appears in the function Essentially the same information as appears in the function header with the addition of the semicolonheader with the addition of the semicolon..

• Function prototype must appear before the statement that call the respective functions and are usually placed at the beginning of the program

• In the above program the line int square (int) ; is the function prototype.

Page 106: C Language Presentation=Mohit Sharma,Udaipur

• A part of the function prototype is the function signature• A function signature is the consist of the name of the function and

order and type of the arguments

• In the above ex..=

int square (int) ; //function signatureint square (int) ; //function signature

• one more thing u need to remember is function signature must be unique for each and every function and u cannot have two functions with the same signature in one program

Page 107: C Language Presentation=Mohit Sharma,Udaipur

Function DefinitionFunction Definitionfunction definition contains the actual implementation of the function .function definition can be divided into two parts=• Function Header• Function Body

Function HeaderFunction Header

return type function name return type function name ( Argument list )( Argument list )argument declaration ;argument declaration ;

( or )( or )

return type ( Argument along with Declaration)return type ( Argument along with Declaration)ex.

int add (x ,y)int add (x ,y) int x , y;int x , y;

(or )

int add (int x, int y )int add (int x, int y )

Page 108: C Language Presentation=Mohit Sharma,Udaipur

Function BodyFunction Body

function body contains the actual code that implements the functionality of the function.

in general function body contains declaration of local variables and statement and generally looks in the following form:

{{ local variable declarations;local variable declarations; function statements;function statements; …………… …………… …… ……................ return ( expression) ;return ( expression) ;}}

Page 109: C Language Presentation=Mohit Sharma,Udaipur

hence, altogether ,

Function Header + Function BodyFunction Header + Function Body

together makes function definition and a complete function definition looks as follows:

return type Function name (Function arguments)return type Function name (Function arguments)

{{

Local Variable Declaration;Local Variable Declaration;

Function Statements ;Function Statements ;

…… ……..............

…………… ……………....

return (expression) ;return (expression) ;

}}

Page 110: C Language Presentation=Mohit Sharma,Udaipur

Function ArgumentsFunction ArgumentsFunction arguments are used to pass input to the function .Arguments are optional and a function can have one or more Arguments

to a function each and every argument at all. when u are pass multiple arguments to the function each and every

argument must be separated by a comma. there are two types of function arguments =Formal Arguments Formal Arguments Actual ArgumentsActual Arguments

Formal ArgumentsFormal Arguments Formal Arguments are valid variables that are used in Function

Header of the function definition in order to store the values of the actual arguments.

Formal Arguments are must be surrounded by parenthesis. must not be terminated by using a semicolon.

Page 111: C Language Presentation=Mohit Sharma,Udaipur

Actual ArgumentsActual Arguments Actual Arguments are the values that are passed to a

Function during a Function Call

An actual argument can be either a variable or constant or valid expression .

one more thing is to be remember is the type and order of the actual arguments must match the formal arguments.

Page 112: C Language Presentation=Mohit Sharma,Udaipur

Function callFunction call• A function is invoked using a function call.

A function call requires the programmer =

• To specify the specific function by name

• “Pass “data to the function that it needs: (arguments)

• Functions optionally return a single “value” to the caller ,which needs to be trapped for further use in the program.

Page 113: C Language Presentation=Mohit Sharma,Udaipur

The function that is invoking another function is refereed as calling functioncalling function , and the function that has been invoked is referred as called functioncalled function..ex. boss to worker analogy

• a boss (the calling function or caller ) tells a worker (the called function) to perform a task and return (i.e. report back) the results when the task is done.

• one more thing we need to remember here is once function call is made (calling function invokes Called Function),

• the program control is transferred from the calling function to the called function , and when the called function finishes its execution ,

• the program control is transferred back to the calling function.

Page 114: C Language Presentation=Mohit Sharma,Udaipur

Return ValueReturn Value• once the called functions finishes its execution, it may

return a value to the calling function informing whether it has finished the execution successfully or not,

• which is commonly refereed as return value a function may or may not send back any value to the calling function.

• if it does, it through a special statement known as return.• while it is possible to pass any no. of arguments to the

called function, but a called function can return only one value to the calling function ,that also by

• using return statement. The return statement can take one of the

following forms:

Page 115: C Language Presentation=Mohit Sharma,Udaipur

return ;

or

return (expression) ;

the first form return doesn’t return any value;it acts simply as the closing brace for the function.the second form of the return statement returns the value of the

expression to the calling function.when return statement is encountered ,the execution of called function gets terminated and the program control is immediately passed back to the calling

function through return statement may or may not return a value to the calling function .

a function may have more than one return statements.this situation arises when the value returned is based on certain

conditions.for example:

Page 116: C Language Presentation=Mohit Sharma,Udaipur

if (x<=0) return 0; else return 1; a function returns an int value by default .however we

can force the function to return a particular type of data by using a type specifier in function header.

example:float circle area (int radius)float squareroot (num) A function that doesn’t return any value to the calling

function simply specify its return type as void void (which means nothing ) void getsdetails() void prime()

Page 117: C Language Presentation=Mohit Sharma,Udaipur

basics of functions

return type function name (type of argument) ; //function prototypemain() //calling function{……………..……………//function callvariable =function name (actual arguments); //called function ………..…………..} return type function name (declaration of formal arguments) //function header{ declaration of local variables function arguments; ………. …………. return value; }

Page 118: C Language Presentation=Mohit Sharma,Udaipur

• Components of a FunctionComponents of a Function• funcrtion headerfuncrtion header• defines the function name,return type and the number and defines the function name,return type and the number and

types of the parameterstypes of the parameters

• ParamertersParamerters• information flow to the functioninformation flow to the function

• Local variablesLocal variables• variables and witin the function (private to the function)created variables and witin the function (private to the function)created

when function is called, ”destroyed”when functions returns.when function is called, ”destroyed”when functions returns.

• Function BodyFunction Body• contains the software that implements the functioncontains the software that implements the function

• Return StaementReturn Staement• specifies the value that is returned to the caller,returns flow of specifies the value that is returned to the caller,returns flow of

execution to the callerexecution to the caller

Page 119: C Language Presentation=Mohit Sharma,Udaipur
Page 120: C Language Presentation=Mohit Sharma,Udaipur

WithoutWithout Return Value Return Value withoutwithout Argument Argument

• Rule :• When the value is not return then it is essential to write void

in definition.

• When the value is return then we can not use void in the definition part.

• when the value is return then we writeint function name;

then we also write int definition; andthen we also write int declaration;

Page 121: C Language Presentation=Mohit Sharma,Udaipur

Calling a function:Calling a function:• a function can be called by simplifying using the function

name in an statement .• example:example:void main(){ int p; p=mul(10 , 4); printf (“ %d ”,p);}• when the compiler encounters a function call, the control is

transferred to the function mul (x , y).• this function is then executed line by line as described and a

value is returned when a return statement is encountered .this value is assigned to p.

Page 122: C Language Presentation=Mohit Sharma,Udaipur

No argumentsNo arguments and and No returnNo return values values

• when a function has no argument ,it does not receive any data from the calling function.

• similarly when n it does not return a value, the calling function does not receive any data from the called function.

Page 123: C Language Presentation=Mohit Sharma,Udaipur

# header file //withoutwithout return value return value withoutwithout argument argument

void main(){ void sum( ); //declaration sum(); //calling the function sum(); //calling the function sum(); //calling the function getch();} void sum() //definition{ int x,y,z; printf( “enter the value of x , y ”); scanf (“%d %d”,&x,&y); z = x + y ; printf (“ the z is % d ”,z”);}

Page 124: C Language Presentation=Mohit Sharma,Udaipur

# header file //WithWith return value return value WithoutWithout argument argumentvoid main(){ int a,b; //data type declare int sum(); // function declaration a= sum( ); //calling the function b=sum( ); //calling the function printf(“%d”,a); printf(“%d”,b); getch();}

int sum() // function definition{ int x,y,z; printf( “enter the value of x , y ”); scanf (“%d %d”,&x,&y); z = x + y ; return(z);}

Page 125: C Language Presentation=Mohit Sharma,Udaipur

# header file // WithoutWithout return value return value WithWith Argument Argumentvoid main(){ int square( int x ) ; //declaration int z,a;

scanf(“%d”,&a);z=square(a);

printf(“%d”,z); getch();} int square (int x) //definition{ int y ;

y = x * x; printf (“%d”,y);}

Page 126: C Language Presentation=Mohit Sharma,Udaipur

# header file //with return value with argumentvoid main(){ int square( int x); // function declaration int z, a; //datatype declare scanf(“%d”,&a); z=square(a); printf(“%d”,b); getch(); } int square (int x) // function definition{ int y ; y =x *x ; return (y);}

Page 127: C Language Presentation=Mohit Sharma,Udaipur

VARIABLEVARIABLE DECLARATIONDECLARATION==

LOCALLOCAL(ONLY FOR SUB PROGRAM)

GLOBALGLOBAL(FOR WHOLE PROGRAM)

FOR EX.

int x,y,z;-->global declaration

main(){subprogram-->function

int p......return 0;}

Page 128: C Language Presentation=Mohit Sharma,Udaipur

Unformatted ConsoleUnformatted Console I/OI/O

get char( ) one character read / scanf (“ %c “ , &x)

putchar( ) one character output

gets( ) string read

puts( ) string output

Page 129: C Language Presentation=Mohit Sharma,Udaipur

The main( ) FunctionThe main( ) Function

Following forms are allowed

• main( )

• int main()

• void main()

• main(void)

• Void main (void)

• int main( void)

Page 130: C Language Presentation=Mohit Sharma,Udaipur

Function Declaration consist of 4 typeFunction Declaration consist of 4 type==

Return type

Function Name

Parameter list / Argument

Semicolon

Page 131: C Language Presentation=Mohit Sharma,Udaipur

Standard library filesStandard library files== conio.h

math.h

ctype.h

string.h

time.h

Page 132: C Language Presentation=Mohit Sharma,Udaipur
Page 133: C Language Presentation=Mohit Sharma,Udaipur

• Defining structures

• a structure is a collection of variables under a single name.

• these variables can be of different types, and each has a name which is used to select it from the structure.

• a structure is a convenient way of grouping several pieces of related information together.

Page 134: C Language Presentation=Mohit Sharma,Udaipur

Declaring structureDeclaring structure• the general form of declaring a structure is as

follows:

struct <structure name>{structure element 1;structure element 2 ;structure element 3; ……………………..

};

Page 135: C Language Presentation=Mohit Sharma,Udaipur

example:

struct student

{

char name[20];

int age;

float height,weight;

};

note: a structure declaration must always terminate with a semicolon.

Page 136: C Language Presentation=Mohit Sharma,Udaipur

Accessing element of structure• in order to access the elements of a structure ,first of all we need to

create an instance variable for structure and then we can access the elements of the structure through its instance3 variable

• we can create an instance variable for a structure either at the time of declaring the structure or anywhere else in the program.

• once we declared the structure we create an instance variable for a structure we can access the structure elements in the following form:

• structure_variable. structure element example:• s1.name;• s1.height• s1.float and so on.

Page 137: C Language Presentation=Mohit Sharma,Udaipur

• initializing the no. of a structure variable• the members of the structure variable can be initializwed either at the time of

declaring the structure variable or any where else in the program

• exmple program for in\itializing structure variable at the time of declaration#include<stdio.h>struct student{ char name[20];int age;float height, weight;};main(){struct students={“mohit”,23,5.5,54,0};clrscr();printf(“student name%s \n “,s.name);printf(“student age%d \n” s.age);printf(“student height %f weight %f \n”,s.height,s.weight);printf(“student height %fweight %f \n “,s.height,s.weight);}

Page 138: C Language Presentation=Mohit Sharma,Udaipur

• output of the above program is as follows:

• student name mohit

• student age 23

• student height 5.5 weight 54

Page 139: C Language Presentation=Mohit Sharma,Udaipur

• array of structuresarray of structures

• in array of structures we store the details of all the students in a class.

• array of structure are similar to the normal array except the difference that they belong to a structure instead of primitive data type.

• the following example gives u a clear idea about the same

#

Page 140: C Language Presentation=Mohit Sharma,Udaipur

#include<stdio.h>struct student{ char name[20];int age;float height, weight;};main(){struct students s[5];int i;clrscr( );for( i=0 ; i<5; i++){printf(“enter student name\n”);scanf(“%s”,&s[i].name);printf(“enter student age”);scanf(“%d”,&s[i] ,age);

printf(“enter student height and weight”);

scanf(“%f %f ,&s[i].height,&s[i].weight);}

Page 141: C Language Presentation=Mohit Sharma,Udaipur

clrscr();for(i=0; i<5; i++){printf(“student name%s \n”,s[i].name);

printf(“student height %f weight %f \n “,s.height,s.weight);printf(“student age %d \n”,s[i].age);printf(“student height %5.2f \n”s[i].height);printf(“student weight %5.2f \n “,s[i].weight);

}getch();}

Page 142: C Language Presentation=Mohit Sharma,Udaipur

• structures and pointers

• a pointer pointing to a structure is referred as structure pointers’• example program to access elements of a structure using pointer

#include<stdio.h>

strucrt student{ char name[20];int age;float height,weight;};main(){struct student s,*ptr=&s;printf(“enter name\n”);scanf(“%s”,&ptr->age);printf(“enter age \n”);scanf(“%d”,&ptr->age);printf(“enter height and weight of the student \n”);scanf(“%f%f”,&ptr->height,&ptr->weight);printf(“name\t%s\n”ptr->name);printf(“age\t%d\n”,ptr->age);printf(“height\t%5.5f \t weight \t %5.2f\n”,ptr->height,ptr->weight)”getch();}

Page 143: C Language Presentation=Mohit Sharma,Udaipur
Page 144: C Language Presentation=Mohit Sharma,Udaipur
Page 145: C Language Presentation=Mohit Sharma,Udaipur
Page 146: C Language Presentation=Mohit Sharma,Udaipur
Page 147: C Language Presentation=Mohit Sharma,Udaipur
Page 148: C Language Presentation=Mohit Sharma,Udaipur
Page 149: C Language Presentation=Mohit Sharma,Udaipur
Page 150: C Language Presentation=Mohit Sharma,Udaipur

File SystemFile System

• File is a collection of Record.File is a collection of Record.

File function in C =File function in C =

• fopenfopen• fclosefclose• fscanffscanf• fprintffprintf• putcputc• putwputw• getcgetc• getwgetw• windwind• ftailftail• fsickfsick

Page 151: C Language Presentation=Mohit Sharma,Udaipur

• File File OperationOperation

• Creation

• updation

• Insertion

• deletion

• modification

• Maintenance

• retrieval

Page 152: C Language Presentation=Mohit Sharma,Udaipur

• Some question of c languageSome question of c language

• who developed c language?• Dennis Ritchie

……………………………………• give 2 ex. of OOP?• c++, java, c sharp……………………………………..

• what is mean by token?operator ,string, identifier

…………………………………….

• what is role of main() in c?…………………………………………

Page 153: C Language Presentation=Mohit Sharma,Udaipur

what are variables? How u create a variable?

first character must be alphabet or underscore(_).

must consist of letters, digits, underscore(_).

keyword / reserve word are not allowed.

only first 31 character are significant.

uppercase and lower case are identical.

must not contain white spaces.

Page 154: C Language Presentation=Mohit Sharma,Udaipur

• list the 3 types of integer supported by c?• octal, hexa, decimal• ……………………………………..• what are escape sequence?• escape sequence character in c

• character escape sequence character

• bell \a• back space \b• horizontal tap \t• vertical tab \v• form feed \f• carrier return \r• back slash \\• null \0• question mark \?…………………………………………………..• what are constants?• int ,char, float

Page 155: C Language Presentation=Mohit Sharma,Udaipur

Q• what are the fundamental data types in c?

……………………………………• what is the range of integer, character, float?

…………………………• name 4 data types modifier?

………………………………..• name the operators in c?

…………………………..• name dynamic data structure?• stack, queue, linked list.

……………………………………

Page 156: C Language Presentation=Mohit Sharma,Udaipur

• write the ways to write main()?

• write the name of user defined data types/

• what is the basic structure of c program/

• write the steps to execute the c program?

• what are the two types of errors?

• what do u mean by semantic errors?

• what are the various c compiler are available?

• name the Linux based c compiler?

• what are the three section of c pre processor?

• what is trigraph sequence?

• name some client side and server side scripting language?

Q

Page 157: C Language Presentation=Mohit Sharma,Udaipur

• basic difference between oops and procedural programming?

• what are the two types of type conversion?

• name all the reserved word in c?

• what is modular programming?

Q

Page 158: C Language Presentation=Mohit Sharma,Udaipur

• Mohit sharma

[email protected]

• Contact for software development and web site development work,projects