Click here to load reader

C Course material

Embed Size (px)

Citation preview

Slide 1

NIELIT Gorakhpur CentreMMMUT Campus, Gorakhpur (UP), PIN-2730101 NIELIT Gorakhpur Centre.CprogrammingFaculty: Fareed Khan

1

2 NIELIT Gorakhpur Centre.IndexTopic of C Language

Chapter No.Topic1Language2Flow Charts3C Language4Data Types and Operator5Decision Making & Control Statement6Loops7Functions8Pointers9Storage Class10C Preprocessor11Structure12File Handling13Command Line Argument14Dynamic Memory Allocation15Linked List

2

Chapter- 01Language

NIELIT Gorakhpur CentreMMMUT Campus, Gorakhpur (UP), PIN-2730103 NIELIT Gorakhpur Centre.What is Language?Programming Language

3

Language

4 NIELIT Gorakhpur Centre.C LANGUAGEWhat is Language

Language is a collection of words and symbols which can be used to perform certain task or activities and to establish a communication between person to person.

In the same manner computer languages are the collection of predefine key words which can be used to perform certain task and to communicate between to entities like between two machines or between human and computers or computers and others peripherals. There are three different level of programming languages. They are:

Machine languages (low level) Assembly languages Procedure Oriented languages (high level)

Slide is Self Explanatory 4

5 NIELIT Gorakhpur Centre.C LANGUAGEWhat is Language

LanguageMachine Languages: Computers are made of No. of electronic components and they all are two state electronic components means they understand only the 0 (pulse) and 1 (non pulse). Therefore the instruction given to the computer must be written using binary numbers. 1and 0. Computers do not understand English or any other language but they only understand or respond to binary numbers (0 and 1). So each computer has its own Machine languages.

Slide is Self Explanatory 5

6 NIELIT Gorakhpur Centre.C LANGUAGEWhat is Language

LanguageAssembly Languages: As it was very tedious to understand and remember 0s representing numerous data and instruction. So to resolve this problem mnemonics codes were developed. For example add is used as symbolic code to represent addition. SUB is used for subtraction. They are the symbolic representation of certain combination of binary numbers .for example S U B Which represents certain actions as computer understand only Machine language instructions a program written in Assembly Language must be translated into Machine languages. Before it can be executed this translation if done by another program called assembler. This assembler will translate mnemonic codes into Machine languages.

Slide is Self Explanatory 6

7 NIELIT Gorakhpur Centre.C LANGUAGEWhat is Language

LanguageProcedure Oriented Languages: In earlier assembly languages assembler programs produced only one Machine languages instruction for every assembly languages instruction. So to resolve this problem now assembler were introduced. Which can produce several machine level instructions for one assembly language instruction. Thus programmer was relieve from the task of writing and instruction for every machine operation performed. These languages contains set of words and symbols and one can write program with the combination of these keywords. These languages are also called high level languages. Basic, Fortran, Pascal and COBOL. The most important characteristic of high level languages is that it is machine independent and a program written in high level languages can be run on any computers with different architecture with no modification or very little modification.

Slide is Self Explanatory 7

8 NIELIT Gorakhpur Centre.Programming Language

All programming languages can be divided into two categories:

LanguageC LANGUAGE

Problem Oriented LanguageOrHigh Level LanguageProblem Oriented LanguageOrLow Level LanguageProgramming Language

Slide is Self Explanatory 8

9 NIELIT Gorakhpur Centre.Programming Language

LanguageC LANGUAGEProblem oriented languages or high languages : Examples of languages falling in this category are FORTRAN, BASIC, Pascal, etc. These languages have been designed to give a better programming efficiency, faster program development. Generally these languages have better programming capability but they are less capable to deal with hardware or Hardware related programming. Machine oriented languages of Low Level Languages : Examples of languages falling in this category are Assembly language and Machine Language. This languages have been designed to give a better machine efficiency i.e. faster program execution. Generally these languages have better hardware programming capability but it is very difficult and tedious to do create complex application like and business application or some commercial application

C as Middle Level Language : C stands in between these two categories. Thats why it is called a Middle Level Language, since it was designed to have both; a relatively good programming efficiency (as compared to Machine Oriented Language) and a relatively good machine efficiency (as compared to Problem Oriented Language).

Slide is Self Explanatory 9

Chapter- 02Flow Chart

NIELIT Gorakhpur CentreMMMUT Campus, Gorakhpur (UP), PIN-27301010 NIELIT Gorakhpur Centre.IntroductionFlow Chart SymbolExamplesAdvantagesLimitation

STARTStatementConditionStatementStatementSTOP

Slide is Self Explanatory

10

11 NIELIT Gorakhpur Centre.Flow Charts

LanguageC LANGUAGEA flowchart is a graphical representation of decisions and their results mapped out in individual shapes that were first developed by Herman Goldstine and John von Neumann in the 1940s. Flowcharts can provide a step-by-step diagram for mapping out complex situations, such as programming code or troubleshooting problems with a Computer.

A diagrammatic representation that illustrates the sequence of operations to be performed to get the solution of a problem.Generally drawn in the early stages of formulating computer solutions. Facilitate communication between programmers and business people/end users. Once the flowchart is drawn, it becomes easy to write the program in any high level language. Must for the better documentation of a complex program.

Slide is Self Explanatory 11

12 NIELIT Gorakhpur Centre.Flow Chart Symbol

LanguageC LANGUAGESymbolDescriptionUsed to indicates the start and end of a flowchart. Single flow line. Only one Start and Stop terminal for each program.Process: Used whenever data is being manipulated. One flow line enters and one flow line exits.Input / Output: Used whenever data is entered (input) or displayed (output). One flow line enters and one flow line exits.Decision: Used to represent operations in which there are two possible selections. One flow line enters and two flow lines exit.Flow line: Used to indicate the direction of flow of control.

Slide is Self Explanatory 12

13 NIELIT Gorakhpur Centre.Flow Chart Symbol

LanguageC LANGUAGE Example 1: Draw a flow chart to show the addition of two no.STARTSTOPAccept no1 & no1Sum=no1+no2Display the sum

Slide is Self Explanatory 13

14 NIELIT Gorakhpur Centre.Flow Chart Symbol

LanguageC LANGUAGE Example 2: Draw a flowchart to find the sum of first 50 natural numbers.

Slide is Self Explanatory 14

15 NIELIT Gorakhpur Centre.Flow Chart Symbol

LanguageC LANGUAGE Example 3: Draw a flowchart to find the largest of three numbers A,B and C.

Slide is Self Explanatory 15

16 NIELIT Gorakhpur Centre.Flow Chart Symbol

LanguageC LANGUAGEExample 4: Draw a flowchart for computing factorial of a given number.

Slide is Self Explanatory 16

17 NIELIT Gorakhpur Centre.Advantages of using Flowcharts

LanguageC LANGUAGECommunication: Flowcharts are better way of communicating the logic of a system to all concerned.Effective analysis: With the help of flowchart, problem can be analyzed in more effective way.Proper documentation: Program flowcharts serve as a good program documentation, which is needed for various purposes.Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and program development phase.Proper Debugging: The flowchart helps in debugging process.Efficient Program Maintenance: The maintenance of operating program becomes easy with the help of flowchart. It helps the programmer to put efforts more efficiently on that part.

Slide is Self Explanatory 17

18 NIELIT Gorakhpur Centre.Limitation of using Flowcharts

LanguageC LANGUAGEComplex logic: Sometimes, the program logic is quite complicated. Alterations and Modifications: Alterations may require re-drawing completely. Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem.

Slide is Self Explanatory 18

Chapter- 03C Language

NIELIT Gorakhpur CentreMMMUT Campus, Gorakhpur (UP), PIN-27301019 NIELIT Gorakhpur Centre.IntroductionHistory of CImportance of CBasic Structure of C programExecution of C programVariableKeywordsConstant in C

Slide is Self Explanatory

19

20 NIELIT Gorakhpur Centre.Introduction

C language is a general purpose and structured programming language developed by 'Dennis Ritchie' at AT &T's Bell Laboratories in the 1972 in USA.

It is also called as 'Procedure oriented programming language.'C is not specially designed for specific applications areas like COBOL (Common Business-Oriented Language) or FORTRAN (Formula Translation). It is well suited for business and scientific applications. It has some various features like control structures, looping statements, arrays, macros required for these applications.

The C language has following numerous features as:FlexibilityPortabilityCompactnessReusability

LanguageC LANGUAGE

Slide is Self Explanatory 20

Language

21 NIELIT Gorakhpur Centre.Introduction

FLEXIBLILITY: C is a powerful and flexible language. C is used for projects as diverse as operating system, word processor, graphics, spreadsheets and even compilers for other language. C is a popular language preferred by professional programmers. As a result, a wide variety of C compilers and helpful accessories are available.

PORTABILITY: C is a portable language. Portable means that a C program written for one computer system can be run on another system with little or no modification. Portability is enhanced by the ANSI standard by C, the set of rules for C compilers.

COMPACTNESS: C is a language of few words, containing only a handful terms, called keywords, which serve as the base on which the languages functionality is built. You might think that a language with more keyword would be more powerful. This isnt true. As you will find that it can be programmed to do any task.

REUSABILITY: C is modular, C code can and should be written in routine called functions. These functions can be reused in other applications or programs. By passing pieces of information to the function, you can create useful, reusable code. C LANGUAGE

Slide is Self Explanatory

21

22 NIELIT Gorakhpur Centre.History of C

LanguageC LANGUAGE

Slide is Self Explanatory

22

23 NIELIT Gorakhpur Centre.History of C

LanguageC LANGUAGEC was evolved from ALGOL, BCPL and B.C was developed by Dennis Ritchie at the Bell Laboratories in 1972.Added new features and concepts like data types.It was developed along with the UNIX operating system.It was strongly integrated with the UNIX operating system.In 1983 American National Standards Institute (ANSI) appointed a technical committee to define a standard for C. The committee approved a version of C in December 1989 which is now known as ANSI C. In 1990 International Standards Organization (ISO) has approved C and this version of C is referred to as C89.

Slide is Self Explanatory

23

24 NIELIT Gorakhpur Centre.

Rich set of built-in functionsOperators can be used to write any complex program.The C compiler combines the capabilities of an assembly language with the features of a high-level language.It is well sited for writing both system software and business packages.Due to variety of data types and powerful operators programs written in C are efficient and fast.There are only 32 keywords in C and its strength lies in its built in functions.C is highly portable. Ability to extend itself.C is a Structured Programming Language (requiring the user to think of a problems in terms of function modules or blocks).Importance of C

LanguageC LANGUAGE

Slide is Self Explanatory 24

25 NIELIT Gorakhpur Centre.Basic Structure of C Program

C program can be viewed a s group of building blocks called functions. A function is a subroutine that may include one or more statement designed to perform a specific task. A C program may contain one or more section as shown below :

Documentation Section Link Section Definition Section Global declaration Section main( ) function section {Declaration PartExecutable Part }Subprogram SectionFunction1 ( ){}Function2 ( ){}

LanguageC LANGUAGE

25

26 NIELIT Gorakhpur Centre.Basic Structure of C Program

LanguageC LANGUAGE Documentation Section:This section contains set of comments lines consist of details like program name, author name and purpose or functionality of the program.

Link Section: This section consist of instructions to be given to the compiler to link functions from the system library. For example if you want to use some mathematical function then you have to define link for math.h file in link section. For Example:# include# include

Definition Section: This section defines all the symbolic constants. For example PI=3.14. By defining symbolic constant one can use these symbolic constant instead of constant value.# define PI 3.14# define Temp 35

Slide is Self Explanatory26

27 NIELIT Gorakhpur Centre.Basic Structure of C Program

LanguageC LANGUAGEGlobal Declaration Section : This section contains the declaration of variables which are used by more then more then one function of the program.

Main Function Section : A main() function is a heart of any C language program. Any C program is made up of 1 or more then 1 function. If there is only 1 function in the program then it must be the main program. An execution of any C program starts with main() function.

Subprogram Or Sub Function Section : They are the code section which are define outside the boundary of main function. This function can be called from any point or anywhere from the program. Generally they are define to solve some frequent tasks.

Slide is Self Explanatory

27

28 NIELIT Gorakhpur Centre.Execution of C Program

C program executes in following 4 (four steps).

LanguageC LANGUAGE

Slide is Self Explanatory28

29 NIELIT Gorakhpur Centre.Execution of C Program

LanguageC LANGUAGE Creating a program : An editor like notepad or WordPad is used to create a C program. This file contains a source code which consists of executable code. The file should be saved as '*.c' extension only.

Compiling the program : The next step is to compile the program. The code is compiled by using compiler. Compiler converts executable code to binary code i.e. object code.

Linking a program to library : The object code of a program is linked with libraries that are needed for execution of a program. The linker is used to link the program with libraries. It creates a file with '*.exe' extension.

Execution of program : The final executable file is then run by dos command prompt or by any other software.

Slide is Self Explanatory29

Language

30 NIELIT Gorakhpur Centre.Variables

Character SetA character refers to the digit, alphabet or special symbol used to data representation. Alphabets: A-Z, a-z Digits : 0-9 Special Characters: ~ ! @ # $ % ^ & * ( ) _ + { } [ ] - < > , . / ? \ | : ; " ' White Spaces :Horizontal tab, Carriage return, New line

Identifieridentifier is the name of a variable that is made up from combination of alphabets, digits and underscore.

VariableIt is a data name which is used to store data and may change during program execution. It is opposite to constant. Variable name is a name given to memory cells location of a computer where data is stored.C LANGUAGE

Slide is Self Explanatory30

Language

31 NIELIT Gorakhpur Centre.Variables

Rules for variables: First character should be letter or alphabet. Keywords are not allowed to use as a variable name. White space is not allowed. C is case sensitive i.e. UPPER and lower case are significant. Only underscore, special symbol is allowed between two characters.C LANGUAGE

Slide is Self Explanatory31

Language

32 NIELIT Gorakhpur Centre.Keywords

There are totally 32 (Thirty Two) keywords used in a C programming.intfloatdoublelongshortsignedunsignedconstifelseswitchbreakdefaultdowhileforregisterexternstaticstructtypedefenumreturnsizeofgotounionautocasevoidcharcontinuevolatile

C LANGUAGE

32

Language

33 NIELIT Gorakhpur Centre.Keywords

C LANGUAGEKeywords are the system defined identifiers.All keywords have fixed meanings that do not change.White spaces are not allowed in keywords.Keyword may not be used as an identifier.It is strongly recommended that keywords should be in lower case letters.

33

Language

34 NIELIT Gorakhpur Centre.Constant in C

A constant is an entity that doesn't change during the execution of a program.Syntax: const data type var_name=expression;Example: const float pi=3.147

Followings are the different types of constants :1. Real Constant :It must have a decimal point which may be positive or negative. Example: +194.143, -416.41

2. Integer Constant :It should not contain a decimal place.It can be positive or negative. Example: 1990, 194, -394

3. Character Constant :It is a single alphabet or a digit or a special symbol enclosed in a single quote.Maximum length of a character constant is 1. Example: 'T', '9', '$'

4. String Constant :It may contain letters, digits, special characters and blank space. Example: Hello friends"C LANGUAGE

Slide is Self Explanatory 34

Language

35 NIELIT Gorakhpur Centre.Backslash Character Constant in C

C supports some special escape sequence characters that are used to do special tasks.Character ConstantMeaning\nNew line (Line break)\bBackspace\tHorizontal Tab\fForm feed\aAlert (alerts a bell)\rCarriage Return\vVertical Tab\?Question Mark\'Single Quote\''Double Quote\\Backslash\0Null

C LANGUAGE

Slide is Self Explanatory 35

Language

36 NIELIT Gorakhpur Centre.Comment in C

Comments in C are of the general of

/* . . . . . * /

Comments can be inserted anywhere you can put a space (blank). Comments are ignored by the C compiler and not included in the executable file.

The */ can be on the next line but then every character between the /* and the */ is ignored by the C compiler.

C LANGUAGE

Slide is Self Explanatory 36

Language

37 NIELIT Gorakhpur Centre.Programming Errors

C LANGUAGE

Syntax Errors The C compiler will catch these errors and give you Error messages.Example: x + 1 = x; (should be x = x+1; for a valid assignment statement)

Run-time Errors The C compiler will not catch these errors.Example: User enters the value 0 and your code reads this value into variable x, and then computes 1/x .

Logical ErrorsThe C compiler will not catch these errors. Program will run and not generate any error messages but results outputted by the program are incorrect.Example: User programs solution using the wrong formula.

Slide is Self Explanatory 37

Chapter- 04

Data Types & Operator

NIELIT Gorakhpur CentreMMMUT Campus, Gorakhpur (UP), PIN-27301038 NIELIT Gorakhpur Centre.Data TypesOperatorsIncrement / Decrement Operator Input / Output Statement

Slide is Self Explanatory

38

39 NIELIT Gorakhpur Centre.Data Types in C

C DATA TYPESPRIMARY DATATYPEDERIVED DATATYPE

INTEGERCHARFLOATVOID

ARRAYPOINTERSTRUCTUREUNIONUSER DEFINED TYPETYPEDEFENUMC LANGUAGE

39

40 NIELIT Gorakhpur Centre.Data Types in C

C LANGUAGE Integer : To access and to store any integer value int data type is use. Cs int data type occupies 2 bytes in the memory. To declare any integer variable : int variable_name;

Float : To access and to store any real value float data type is use. Cs float data type occupies 4 bytes in the memory. To declare any float variable : float variable_name;

Character : To access and to store single character it use char data type in C. Char data type occupies 1 bytes. It means that char data type use 1 byte of memory to store some character value. Declaration of character variable : char variable_name;

40

Language

41 NIELIT Gorakhpur Centre.Data Types in C

KeywordFormat SpecifierSizeData Rangechar%c1 Byte-128 to +127unsigned char%c1 Byte0 to 255int%d2 Bytes-32768 to +32767long int%ld4 Bytes-231 to +231unsigned int%u2 Bytes0 to 65535float%f4 Bytes-3.4e38 to +3.4e38double%lf8 Bytes-1.7e38 to +1.7e38long double%Lf10Bytes-3.4e38 to +3.4e38

Data type can be defined as the type of data of variable or constant store.Followings are the most commonly used data types in C.C LANGUAGE

Slide is Self Explanatory 41

Language

42 NIELIT Gorakhpur Centre.Operators in C

Operator is a symbol that is used to perform operations.Followings are the most commonly used data types in C.Operator NameOperatorsAssignment=Arithmetic+ , - , *, /, %Logical&&, ||, !Relational, =, ==, !=Shorthand+=, -=, *=, /=, %=Unary++, --ConditionalY=(x>9)? 100 :200 ;Bitwise&, |, ^, , ~

C LANGUAGE

Slide is Self Explanatory 42

43 NIELIT Gorakhpur Centre.Arithmetic Operators

LanguageArithmetic operators are used to perform numerical calculations among the values.OperatorMeaning+Addition-Subtraction *Multiplication/Division%Modulo Division

C LANGUAGE

43

44 NIELIT Gorakhpur Centre.Arithmetic Operators

LanguageC LANGUAGEExample:#includeint main(){ int a, b, add, sub, mul, div, rem; printf("Enter a, b values : "); scanf("%d%d",&a,&b); // Reading two values add=a+b; // Addition Operator sub=a-b;// Subtraction Operator mul=a*b;// Multiplication Operator div=a/b;// Division Operator rem=a%b;// Remainder (Modulo) Operator printf("Result of addition is=%d\n", add); printf("Result of subtraction=%d\n", sub); printf("Result of multiplication is=%d\n", mul); printf("Result of division is=%d\n", div); printf("Result of remainder=%d\n",rem); return 0; }

44

45 NIELIT Gorakhpur Centre.Logical Operators

LanguageThese operators are used for testing more than one condition and making decisions.C has three logical operators they are:OperatorMeaning&&Logical AND| |Logical OR!Logical NOT

C LANGUAGE

45

46 NIELIT Gorakhpur Centre.Logical Operators

LanguageC LANGUAGEExample:#includevoid main(){ int a, b; printf(Enter values for a and b : "); scanf(%d %d", &a, &b); printf("\n %d",(a value of a is %d", a>b);printf("\n The >= value of a is %d", a>=b);printf("\n The == value of a is %d", a==b);printf("\n The != value of a is %d", a!=b);}C LANGUAGE

48

49 NIELIT Gorakhpur Centre.Increment & Decrement Operator

C includes a unary increment operator (++) and decrement operator (--).Increment and decrement operators increase and decrease a value stored in a number variable by 1.For example, the expression,count = count + 1; //increment the value of count by 1 is equivalent to count++;

Operator Use Description++ i++ Increments i by 1; evaluates to the value of i before it was incremented++++iIncrements i by 1; evaluates to the value of i after it was incremented-- i--Decrements i by 1; evaluates to the value of i before it was decremented-- --i Decrements i by 1; evaluates to the value of i after it was decrementedFor example:int i = 10,int j = 3;int k = 0;k = ++j + i; //will result to k = 4+10 = 14k = j++ + i; //will result to k = 3+10 = 13

LanguageC LANGUAGE

49

50 NIELIT Gorakhpur Centre.Increment & Decrement Operator

Example:#includevoid main(){ int a,b,c; printf("Enter the values for a and b :"); scanf("%d %d", &a, &b); printf("\n The value of c is %d", c=++a); printf("\n The value of c is %d", c=a++); printf("\n The value of c is %d", c=--b); printf("\n The value of c is %d", c=b--);}

LanguageC LANGUAGE

50

51 NIELIT Gorakhpur Centre.Conditional Operator (? :)

The conditional operator ? : is a ternary operator. This means that it takes in three arguments that together form a conditional expression.

Syntax:

exp1 ? exp2 : exp3;

Where in exp1 is a Boolean expression whose result must either be true or false. If exp1 is true, exp2 is the value returned. If it is false, then exp3 is returned.

LanguageC LANGUAGE

51

52 NIELIT Gorakhpur Centre.Conditional Operator (? :)

Example: void main(){int x;printf("enter any number");scanf("%d",&x);x>0? printf("Positive"):printf("Negative");}

LanguageC LANGUAGE

52

53 NIELIT Gorakhpur Centre.Bitwise Operator

LanguageThese operators works on bit level Applied to Integers only

OperatorMeaning&Bitwise AND|Bitwise OR^Bitwise Exclusive OR>Shift Right~Ones Complement

C LANGUAGE

Slide is Self Explanatory

53

54 NIELIT Gorakhpur Centre.Example (Bitwise Operator)

LanguageLet A=0x56 and B=0x32

A & B ( Bitwise AND )0 1 0 1 0 1 1 00 0 1 1 0 0 1 0---------------------0 0 0 1 0 0 1 0 ---------------------

A ^ B ( Bitwise XOR )0 1 0 1 0 1 1 00 0 1 1 0 0 1 0---------------------0 1 1 0 0 10 0---------------------

A | B ( Bitwise OR )0 1 0 1 0 1 1 00 0 1 1 0 0 1 0---------------------0 1 1 1 0 1 1 0 ---------------------

~ A ( Complement )0 1 0 1 0 1 1 0---------------------1 0 1 0 1 0 0 1---------------------C LANGUAGE

Slide is Self Explanatory

54

55 NIELIT Gorakhpur Centre.Example (Bitwise Operator)

LanguageLet A=0x56

A 2 ( Right Shift )

0 1 0 1 0 1 1 0 >> 1 0 1 0 1 0 1 1 ( 0x2B)

NOTE: For multiply given number by two, left shifted by one time, i.e., a1C LANGUAGE

55

56 NIELIT Gorakhpur Centre.Example (Bitwise Operator)

LanguageExample: void main(){ int x,y; clrscr(); printf(Enter value of x:); scanf(%d,&x); y=x3);}

Output:Enter value of x:16Left shifted data=128Right shifted data=2C LANGUAGE

56

57 NIELIT Gorakhpur Centre.Input Output Statements in C

Printf() Function : Printf() function is use to display something on the console or to display the value of some variable on the console.

The general syntax for printf() function is as follows printf(,);

Scanf() Function : Scanf() function is use to read data from keyboard and to store that data in the variables.

The general syntax for scanf() function is as follows. Scanf(format specifier,&variable);

LanguageC LANGUAGE

Slide is Self Explanatory 57

58 NIELIT Gorakhpur Centre.First Program of C Language

Language#include#includevoidmain(){printf(Welcome to NIELIT");getch();}

Description of the above C Program:

#include includes thestandard input outputlibrary functions. The printf() function is defined in stdio.h .#include includes theconsole input outputlibrary functions. The getch() function is defined in conio.h file.void main()Themain() function is the entry point of every programin c language. The void keyword specifies that it returns no value.printf()The printf() function isused to print dataon the console.getch()The getch() functionasks for a single character. Until you press any key, it blocks the screen.C LANGUAGE

Slide is Self Explanatory 58

Chapter- 05

Decision Making / Control Statement

NIELIT Gorakhpur CentreMMMUT Campus, Gorakhpur (UP), PIN-27301059 NIELIT Gorakhpur Centre.If Statement If-else StatementNested If-else StatementSwitch Case

Slide is Self Explanatory

59

60 NIELIT Gorakhpur Centre.Decision Making/ Conditional Statements

Decision Making / Conditional Statements:

C program executes program sequentially. Sometimes, a program requires checking of certain conditions in program execution.

Followings are the different conditional statements used in C.If Statement If-else StatementNested If-else StatementSwitch Case

LanguageC LANGUAGE

Slide is Self Explanatory

60

Language

61 NIELIT Gorakhpur Centre.Decision Making/ Conditional Statements

If Statement:This is a conditional statement used in C to check condition or to control the flow of execution of statements.

Syntax: if (condition) { statements; }

In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and executes the block of statements associated with it. If it returns false, then program skips the braces.C LANGUAGE

61

62 NIELIT Gorakhpur Centre.Decision Making/ Conditional Statements

Example of If Statement:

#includemain( ) { int qty, dis = 0 ; float rate, tot ; printf ( "Enter quantity and rate " ) ; scanf ( "%d %f", &qty, &rate) ; if ( qty > 1000 ) dis = 10 ;tot = ( qty * rate ) - ( qty * rate * dis / 100 ) ; printf ( "Total expenses = Rs. %f", tot ) ; }

LanguageC LANGUAGE

62

Language

63 NIELIT Gorakhpur Centre.Decision Making/ Conditional Statements

If-Else Statement:This is also one of the most useful conditional statement used in C to check conditions.

Syntax: if(condition) { true statements; } else { false statements; }

In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and executes the block of statements associated with it. If it returns false, then it executes the else part of a program.C LANGUAGE

63

Language

64 NIELIT Gorakhpur Centre.Decision Making/ Conditional Statements

Example:main( ) { float bs, gs, da, hra ; printf ( "Enter basic salary " ) ; scanf ( "%f", &bs ) ; if ( bs < 1500 ) { hra = bs * 10 / 100 ; da = bs * 90 / 100 ; } else { hra = 500 ; da = bs * 98 / 100 ; } gs = bs + hra + da ; printf ( "gross salary = Rs. %f", gs ) ; } C LANGUAGE

64

Language

65 NIELIT Gorakhpur Centre.Decision Making/ Conditional Statements

Nested If-Else Statement:It is a conditional statement which is used when we want to check more than 1 conditions at a time in a same program. The conditions are executed from top to bottom checking each condition whether it meets the conditional criteria or not. Syntax: if(condition) { if(condition) { statements; } else { statements; } } else { statements; } In this syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and again checks the next condition. If it is true then it executes the block of statements associated with it else executes else part.C LANGUAGE

65

Language

66 NIELIT Gorakhpur Centre.Decision Making/ Conditional Statements

Example:#includemain( ) { int i ; printf ( "Enter either 1 or 2 " ) ; scanf ( "%d", &i ) ; if ( i == 1 ) printf ( "You are Welcome !" ) ; else { if ( i == 2 ) printf ( I m great" ) ; else printf ( I m the best !" ) ; } } C LANGUAGE

66

Language

67 NIELIT Gorakhpur Centre.Decision Making/ Conditional Statements

Switch case Statement :

C LANGUAGEThis is a multiple or multi-way branching decision making statement. When we use nested if-else statement to check more than 1 conditions then the complexity of a program increases in case of a lot of conditions. So to overcome this problem, C provides 'switch case. Switch case checks the value of a expression against a case values, if condition matches the case values then the control is transferred to that point.

67

Language

68 NIELIT Gorakhpur Centre.Decision Making/ Conditional Statements

Example :

In this syntax, switch, case, break are keywords.expr1, expr2 are known as 'case labels.'Break statement causes an exit from switch statement.Default case is optional case. When neither any match found, it executesSyntax: switch (expression) { case expr1: statements; break; case expr2: statements; break;..case expr N: statements; break; default: statements;break; }Note: The break statement is needed so that once a case has been executed, it will skip all the other cases and go outside the switch statement. If the break statement is omitted, the execution will be carried out to the next alternatives until the next break statement is found.C LANGUAGE

68

Language

69 NIELIT Gorakhpur Centre.Decision Making/ Conditional Statements

#include#includemain(){ int x,i; clrscr(); printf("enter any digit no."); scanf("%d",&x); for(i=0;x!=0;x/=10) i++; switch(i) { case 1: printf("One Digit No."); break; case 2: printf("Two Digit No."); break;case 3: printf("Three Digit No."); break; case 4: printf("Four Digit No."); break; case 5: printf("Five Digit No."); break; default: printf("Wrong Input"); }getch();}Example of Switch CaseC LANGUAGE

Slide is Self Explanatory

69

Chapter- 06

Loop

NIELIT Gorakhpur CentreMMMUT Campus, Gorakhpur (UP), PIN-27301070 NIELIT Gorakhpur Centre.While LoopFor LoopDo while LoopBreak and Continue StatementGoto Statement

Slide is Self Explanatory

70

71 NIELIT Gorakhpur Centre.Looping / Iterative Statements

'A Loop' is a part of code of a program which is executed repeatedly.A Loop is used using condition. The repetition is done until condition becomes condition true.A loop declaration and execution can be done in following ways.

Check condition to start a loopInitialize loop with declaring a variable.Executing statements inside loop.Increment or decrement of value of a variable.

Types of looping statements :Basically, the types of looping statements depends on the condition checking mode.

Condition checking can be made in two ways as : Before loop and after loop.

So, there are 2(two) types of looping statements.Entry Controlled LoopExit Controlled Loop

LanguageC LANGUAGE

Slide is Self Explanatory

71

72 NIELIT Gorakhpur Centre.Looping / Iterative Statements

Entry controlled loop :In such type of loop, the test condition is checked first before the loop is executed.Some common examples of this looping statements are :

while loopfor loop

Exit controlled loop :In such type of loop, the loop is executed first. Then condition is checked after block of statements are executed.

The loop executed atleast one time compulsorily. Some common example of this looping statement is :

do-while loop

LanguageC LANGUAGE

Slide is Self Explanatory

72

Language

73 NIELIT Gorakhpur Centre.Looping / Iterative Statements

While loop :This is an entry controlled looping statement. It is used to repeat a block of statements until condition becomes true.

Syntax: while(condition) { statements;increment/decrement; }

In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the loop and executes the block of statements associated with it. At the end of loop increment or decrement is done to change in variable value. This process continues until test condition satisfies.C LANGUAGE

73

Language

74 NIELIT Gorakhpur Centre.Looping / Iterative Statements

Example of While loop :C LANGUAGE

#include#includemain(){ int i=1; clrscr(); while(i=75)

Replace statement:#define ALERT printf(Security Alert);

Defined macro name can be used as a part of definition of other macro name.

#define MIN 1#define MAX 9#define MIDDLE (MAX-MIN)/2

No text substitution occur if the identifier is within a quoted string.

Slide is Self Explanatory

124

125 NIELIT Gorakhpur Centre.Macro Expansion

LanguageC LANGUAGE Macro With ArgumentsMacros can have arguments, same as functions#define ISEXCELLENT(x) (x >= 75)#define ISLOWER(x) (x>=97 && x=97 && x 0 ) { fputs ( s, fp ) ; fputs ( "\n", fp ) ; } fclose ( fp ) ; } /* Receives strings from keyboard and writes them to file */

Slide is Self Explanatory

188

Language

189 NIELIT Gorakhpur Centre.String I/O function in Files

C LANGUAGE#includemain( ) { FILE *fp ; char s[80] ; fp = fopen ( fun.txt", "r" ) ; if ( fp == NULL ) { puts ( "Cannot open file" ) ; exit( ) ; } while ( fgets ( s, 79, fp ) != NULL ) printf ( "%s" , s ) ; fclose ( fp ) ; } /* Reads strings from the file and displays them on screen */

Slide is Self Explanatory

189

Language

190 NIELIT Gorakhpur Centre.Modifying a File

C LANGUAGEA file can be accessed in two ways:Serial accessRandom accessGenerally all the text files are considered to be sequential files because lines of text(also called records) are stored in a fileThe beginning of each record in a sequential file is unpredictableWhereas, in random access files, all the records are in same length.To modify the content of a file, open the file with read and write mode (r+ or w+ or a+)Generally r+ mode is used for both reading and writing operation. The procedure is as follows:Initialize a pointer variableOpen the file in read and write modeRead data from file and Print itMove the file pointer to the place where we have the data to be modified andre-write the new data in that place.Repeat steps 3 and 4 till the end of file reaches.Stop the Process

Slide is Self Explanatory

190

Language

191 NIELIT Gorakhpur Centre.Modifying a File

C LANGUAGE#includestruct stock{int itid, qty;char n[100];float rate;}it;void main(){FILE *fp; int ch; int r = 0;fp = fopen(item.c, r+);if(fp==NULL){printf(Unable to open item.c);}else{do{fread(&it, sizeof(it),1,fp);printf(\n%d %s %d %f, it.itid, it.n, it.qty, it.rate);printf(\n Press 1 to change it?);scanf(%d,&ch);if(ch==1){printf(\n Enter Itemid ItemName Quantity & Price);scanf(%d%s%d%f, &it.itid, it.n, &it.qty, &it.rate);fseek(fp, r*sizeof(it), 0);fwrite(&it, sizeof(it),1,fp);}r++;}while(!feof(fp));fclose(fp);}}

Slide is Self Explanatory

191

Language

192 NIELIT Gorakhpur Centre.Formatted I/O Functions

C LANGUAGEUsing formatted I/O functions, fprintf() and fscanf(), numbers, characters or string can be read from file or written onto file according to our requirement format.

fprintf(): is formatted output function which is used to write integer, float, char or string value to a file.Syntax:fprintf(fp,control_string, list_of variables);

fscanf(): is formatted input function which is used to read integer, float, char or string value from a file.Syntax:fscanf(fp,control_string, &list_of variables);

Slide is Self Explanatory

192

Language

193 NIELIT Gorakhpur Centre.Formatted I/O Functions

C LANGUAGEvoid main(){FILE *fp;char name[20];int roll;char address[20];float marks;clrscr();fp=fopen("C:\\student.txt", "w");if(fp==NULL){printf("\n File cannot be created or opened.");exit();}printf("\n Enter name of student:\t");gets(name);printf("\n Enter roll number of %s:\t", name);scanf("%d", &roll);fflush(stdin);

/* Program to create a file named student.txt and write name, roll, address and marks of a student to this file*/printf("\n Enter address of %s:\t", name);gets(address);printf("\n Enter marks of %s:\t", name);scanf("%f", &marks);printf("\n Now writing data to file...");fprintf(fp, "Name=%s\n Roll=%d\n Address=%s\n Marks=%.2f", name, roll, address, marks);printf("\n Completed");fclose(fp);getch();}

Slide is Self Explanatory

193

Language

194 NIELIT Gorakhpur Centre.Error Situations during I/O Operations

C LANGUAGETrying to read beyond the end-of-file mark.Trying to use a file that has not been opened.Trying to perform an operation on a file, when the file is opened for another type of operation.Opening a file with an invalid filename.

Slide is Self Explanatory

194

Language

195 NIELIT Gorakhpur Centre.Error Handling Functions

C LANGUAGEI/O errors can be detected using two status-inquiry library functions: feof() and ferror().feof(): It is used to test for an end-of-file condition. It takes a FILE pointer as its only argument and returns a nonzero integer value if all of the data from the specified file has been read, and returns zero otherwise. If fp is a pointer to a file that has just been opened for reading, then the statement

if(feof(fp)) printf(End of data);would display the message End of data on reaching the end-of-file condition.

ferror(): This function reports the status of the file indicated. It takes a FILE pointer as its argument and returns a nonzero integer if an error has been detected up to that point, during processing. It returns zero otherwise. So the statement

if(ferrorfp)!=0) printf(An error has occured);would print the error message, if the reading is not successful.

Slide is Self Explanatory

195

Language

196 NIELIT Gorakhpur Centre.Functions used in Random access

C LANGUAGEftell() This function takes a file pointer as argument and returns a number of type long, that indicates the current position of the file pointer within the file. This function is useful in saving the current position of a file, which can be used later in the program.Syntax: n=ftell(fp);Here, n would give the relative offset (in bytes) of the current position. This means that n bytes have already been read (or written).

Slide is Self Explanatory

196

Language

197 NIELIT Gorakhpur Centre.Functions used in Random access

C LANGUAGE rewind(): This function takes a file pointer as argument and resets the current position of the file pointer to the start of the file. Syntax:rewind(fp);

What these statements do?: rewind(fp); n=ftell(fp);

Here, n would be assigned 0, because file position has been set to the start of the file by rewind().

Note: The first byte in the file is numbered as 0, second as 1, and so on.

Slide is Self Explanatory

197

Language

198 NIELIT Gorakhpur Centre.Functions used in Random access

C LANGUAGE fseek(): This function is used to move the file pointer to a desired position within a file.Syntax:fseek(fp,offset,position);where fp is a file pointer, offset is a number or variable data type long, and position is an integer numberThe offset specifies the number of positions (bytes) to be moved from the location specified by position.The position can have one of the following 3 values:

ValueMeaning0Beginning of file1Current Position2End of file

Slide is Self Explanatory

198

Language

199 NIELIT Gorakhpur Centre.Functions used in Random access

C LANGUAGEThe offset may be positive, meaning move forwards, or negative, meaning move backwards.Examples:StatementMeaningfseek(fp, 0L, 0);Move file pointer to beginning of file. (Same as rewind.)fseek(fp, 0L, 1);Stay at the current position. (File pointer is not moved.)fseek(fp, 0L, 2);Move file pointer past the last character of the file. (Go to the end of file.)fseek(fp, m, 0);Move file pointer to (m+1)th byte in the file.fseek(fp, m, 1);Move file pointer forwards by m bytes.fseek(fp, -m, 1);Move file pointer backwards by m bytes from the current position.fseek(fp, -m, 2);Move file pointer backwards by m bytes from the end. (Positions the file pointer to the mth character from the end.)

Slide is Self Explanatory

199

Language

200 NIELIT Gorakhpur Centre.Functions used in Random access

C LANGUAGE

fseek()When the operation is successful, fseek() returns a 0 (zero).If we attempt to move the file pointer beyond the file boundaries, an error occurs and fseek() returns -1 (minus one).It is good practice to check whether an error has occurred or not, before proceeding further.

Slide is Self Explanatory

200

Chapter- 14

Command Line Argument

NIELIT Gorakhpur CentreMMMUT Campus, Gorakhpur (UP), PIN-273010201 NIELIT Gorakhpur Centre.

Slide is Self Explanatory

201

Language

202 NIELIT Gorakhpur Centre.Command Line Argument

C LANGUAGE

It is a parameter supplied to a program when the program is invoked. This parameter may represent a filename the program should process.

For example, if we want to execute a program to copy the contents of a file named X_FILE to another one named Y_FILE, then we may use a command line like

C:\TC>PROGRAM X_FILE Y_FILE

PROGRAM is the filename where the executable code of the program is stored. This eliminates the need for the program to request the user to enter the filenames during execution.

Slide is Self Explanatory

202

Language

203 NIELIT Gorakhpur Centre.Command Line Argument

C LANGUAGE

How do these parameters get into the program?We know that every C program should have one main function and that it marks the beginning of the program.

But what we have not mentioned so far is that it can also take arguments like other functions. In fact main can take two arguments called argc and argv and the information contained in the command line is passed on to the program through these arguments, when main is called up by the system.

The variable argc is an argument counter that counts the number of arguments on the command line. The argv is an argument vector and represents an array of character pointers that point to the command line arguments

Slide is Self Explanatory

203

Language

204 NIELIT Gorakhpur Centre.Command Line Argument

C LANGUAGE

The size of this array will be equal to the value of argc. For instance, for the command line given above, argc is three and argv is array of three pointers to strings as shown below:

argv[0] PROGRAMargv[1] X_FILEargv[2] Y_FILE

In order to access the command line arguments, we must declare the main function and its parameters as follows:

main(argc,argv);int argc;char *argv[];

The first parameter in the command line is always the program name and therefore argv[0] always represents the program name.

Slide is Self Explanatory

204

Language

205 NIELIT Gorakhpur Centre.Command Line Argument

C LANGUAGE

Example: Command Line Argument#include#includevoid main(argc,argv)int argc;char *argv[];{FILE *fp;int i;char word[15];clrscr();fp = fopen(argv[1],"w");printf("\nNo.of arguments in Command line=%d\n\n",argc);for(i=2;inext!=NULL) q=q->next; q->next=temp; } }

Slide is Self Explanatory

224

Language

225 NIELIT Gorakhpur Centre.Operations on Link List

C LANGUAGE

Function for display a Linked Listvoid display(){ struct record *p; if(head==NULL) { printf("List is Empty"); return; } p=head; printf("\nList is :\n"); while(p!=NULL) { printf("\n%d",p->rno); p=p->next; } return;}

Slide is Self Explanatory

225

Language

226 NIELIT Gorakhpur Centre.Operations on Link List

C LANGUAGE

Function for Searching a Linked Listvoid search (int d){struct record *p;clrscr();p=head;while(p!=NULL){if(p->rno==d){printf("\n%d",p->rno);getch();return;}p=p->next;}if(p==NULL)printf("Element not found");}

Slide is Self Explanatory

226

Language

227 NIELIT Gorakhpur Centre.Operations on Link List

C LANGUAGE

Function for insert any new node before any node in a Linked Listvoid insbef(int n){ struct record *p,*temp,*h; h=head; temp=malloc(sizeof(struct record)); printf("\nEnter the roll no."); scanf("%d",&temp->rno);if(h->rno==n) { head=temp; temp->next=h; return; } while(h!=NULL) { p=h; h=h->next; if(h->rno==n) { p->next=temp; temp->next=h; return; } } printf("\n Roll Number not found"); return; }

Slide is Self Explanatory

227

Language

228 NIELIT Gorakhpur Centre.Operations on Link List

C LANGUAGE

Function for insert any new node after any node in a Linked Listvoid insaft(int n){struct record *p,*temp,*h;h=head;temp=malloc(sizeof(struct record));printf("\nEnter the roll no.");scanf("%d",&temp->rno);p=h->next;while(h!=NULL){if(h->rno==n){if(h->next==NULL)temp->next=NULL;elsetemp->next=p;h->next=temp;return; }h=p;p=p->next;}printf("\n Roll Number not found");return;}

Slide is Self Explanatory

228

Language

229 NIELIT Gorakhpur Centre.Operations on Link List

C LANGUAGE

Function for delete any node in a Linked Listvoid del (int n){struct record *temp,*q;if(head->rno==n){temp=head;head=head->next;free(temp);return;}q=head;while(q->next->next!=NULL){if(q->next->rno==n){temp=q->next;q->next=temp->next;free(temp);return;}q=q->next;}if(q->next->rno=n){temp=q->next;free(temp);q->next=NULL;return;}printf("\nRoll number not found");}

Slide is Self Explanatory

229

Language

230 NIELIT Gorakhpur Centre.Advantages of Link List

C LANGUAGE

We can dynamically allocate memory space as neededWe can release the unused space in the situation where the allocated space seems to be more.Operation related to data elements like insertions or deletion are more simplified.Operation like insertion or deletion are less time consuming.Linked lists provide flexibility in allowing the items to be arranged efficiently.

Slide is Self Explanatory

230

Language

231 NIELIT Gorakhpur Centre.Advantages of Link List

C LANGUAGE

Linked List is Dynamic data Structure .Linked List can grow and shrink during run time.Efficient Memory Utilization ,i.e no need to pre-allocate memoryFaster Access time, can be expanded in constant time without memory overheadLinear Data Structures such as Stack, Queue can be easily implemented using Linked listWe can release the unused space in the situation where the allocated space seems to be more.Operation related to data elements like insertions or deletion are more simplified.Operation like insertion or deletion are less time consuming.Linked lists provide flexibility in allowing the items to be arranged efficiently.

Slide is Self Explanatory

231

Language

232 NIELIT Gorakhpur Centre.Disadvantages of Link List

C LANGUAGE

They have a tendency to use more memory due to pointers requiring extra storage space.Nodes in a linked list must be read in order from the beginning as linked lists are inherently sequential access.Nodes are stored in-contiguously, greatly increasing the time required to access individual elements within the list.Difficulties arise in linked lists when it comes to reverse traversing. For instance, singly linked lists are cumbersome to navigate backwards and while doubly linked lists are somewhat easier to read, memory is wasted in allocating space for a back pointer.

Slide is Self Explanatory

232

233 NIELIT Gorakhpur Centre.

Thank you

233